Fork Parent Child Date

I need the parent process to interact with each child separately.

I have children who need to communicate with the parent separately from other children.

Is there a way for a parent to have a private communication channel with each child?

Also, can a child, for example, send a parent variable struct?

I am new to such things, so any help is appreciated. Thanks you

+6
source share
1 answer

(I just suppose we are talking about Linux here)

As you probably learned, fork() itself will simply duplicate the calling process, it does not handle IPC .

From the fork manual:

fork () creates a new process, duplicating the calling process. The new process, called the child, is an exact duplication of the calling process, called the parent.

The most common way to handle IPC when you fork () is to use channels, especially if you want "private communication with every child." Here's a typical and simple usage example, similar to the one you can find in the pipe manual (return values ​​are not checked):

  #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[1]); // close the write-end of the pipe, I'm not going to use it 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 exit(EXIT_SUCCESS); } else // if I am the parent then { close(pipefd[0]); // close the read-end of the pipe, I'm not going to use it write(pipefd[1], argv[1], strlen(argv[1])); // send the content of argv[1] to the reader close(pipefd[1]); // close the write-end of the pipe, thus sending EOF to the reader wait(NULL); // wait for the child process to exit before I do the same exit(EXIT_SUCCESS); } return 0; } 

The code is pretty clear:

  • Parent Forks ()
  • The child reads () from the pipe until the EOF
  • Parent writes () to the phone, then closes () he
  • Dates were shared, cheers!

From there, you can do whatever you want; just remember to check your return values ​​and read the dup , pipe , fork , wait ... instructions, they come in handy.

There are also many other ways to exchange data between processes, they are of interest to you, although they do not meet your "private" requirement:

or even a simple file ... (I even used SIGUSR1 / 2 signals to send binary data between processes once ... But I would not recommend this haha.) And probably something else I'm talking about now I don’t think so.

Good luck.

+23
source

All Articles