Question

I'm a student working on a Unix socket/network programming project in C/C++. I'm writing a simple server that can receive TCP messages from multiple clients. Following this guide I've written the server to accept() incoming client connections and then fork() to deal with sending some messages back/forth to each client. So far it's all been pretty easy.

Now, I need to take the data gathered in each fork()-ed child process, pass it back to the parent process that did the accept()-ing, and allow the parent to continue running with the collected data and let each child return 0;. (1 process -> many processes collecting data -> 1 process with all data)

I don't know the best way to do this. My course teaches networking, not managing processes in Unix. How do child processes send data back to the parent? Or, can they somehow share data among themselves? Or, am I approaching this the wrong way entirely?

Was it helpful?

Solution

The common way to make communication between forked child server and its parent is pipe. Here is an example:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int
main(int argc, char * argv[])
{
   int pipefd[ 2];
   pid_t cpid;
   char buf;

   pipe( pipefd); // create the pipe
   cpid = fork(); // duplicate the current process
   if (cpid == 0) // if I am the child then
   {
       close( pipefd[ 0]); // close the read-end of the pipe
       write( pipefd[ 1], argv[0], strlen(argv[0])); // send name to the server
       close( pipefd[ 1]); //close the write-end of the pipe,
                           //send EOF to the server
       exit( EXIT_SUCCESS);
   }
   else // if I am the parent then
   {
       close( pipefd[ 1]); // close the write-end of the pipe
       while ( read( pipefd[ 0], &buf, 1) > 0) // read while EOF
           write( 1, &buf, 1);
       write( 1, "\n", 1);
       close( pipefd[0]); // close the read-end of the pipe
       wait( NULL); // wait for the child process to exit before I do the same
       exit( EXIT_SUCCESS);
   }
   return 0;
}

you can also use shared memory or sockets on localhost.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top