I am doing a simple project in C involving fork()
and socketpairs
. The program forks a process then creates a socketpair for the processes to talk to one another. The parent process reads lines from stdin one at a time until EOF, and then sends the lines one by one the the child. The child converts the lines to uppercase and sends them back to the parent, who sends them to stdout. Here is my code
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(int argc, char *argv[]) {
/* code */
int returnCode, status, socket[2], j;
char* buffer;
size_t bufferSize = 100;
size_t line;
buffer = (char *)malloc(bufferSize * sizeof(char));
socketpair(AF_UNIX, SOCK_STREAM, 0, socket);
returnCode = fork();
if(returnCode == -1){
printf("Fork failed\n");
}
if(returnCode > 0){
while(getline(&buffer, &bufferSize, stdin) != -1){
write(socket[1], buffer, bufferSize);
read(socket[1], buffer, bufferSize);
printf("%s", buffer);
}
}
else{
read (socket[0], buffer, bufferSize);
for(j = 0; j[buffer];j++){
buffer[j] = toupper(buffer[j]);
}
write(socket[0], buffer, bufferSize);
}
return 0;
}
My program prints the first line from stdin capitalized, but then it hangs. I have to ctrl-c to exit. How do i get the sockets to loop thru until EOF printing the modified lines?
My program prints the first line from stdin capitalized, but then it hangs. I have to ctrl-c to exit. How do i get the sockets to loop thru until EOF printing the modified lines?
Your child process's routine (i.e. the one that does the toupper() calls) only calls read() one time, and then calls write() one time, and then exits. That is why only one line is processed. To get it to do multiple lines, you'd need to put the code into a loop:
[...]
else{
while(read(socket[0], buffer, bufferSize) > 0)
{
for(j = 0; j[buffer];j++){
buffer[j] = toupper(buffer[j]);
}
write(socket[0], buffer, bufferSize);
}
}
return 0;
}