c - Fork parent child communication -


i need way parent process communicate each child separately.

i have children need communicate parent separately other children.

is there way parent have private communication channel each child?

also can child example, send parent struct variable?

i'm new these kind of things appreciated. thank you

(i'll assume we're talking linux here)

as found out, fork() duplicate calling process, not handle ipc.

from fork manual:

fork() creates new process duplicating calling process. new process, referred child, exact duplicate of calling process, referred parent.

the common way handle ipc once forked() use pipes, if want "a private comunication chanel each child". here's typical , easy example of use, similar 1 can find in pipe manual (return values 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 pipe        cpid = fork(); // duplicate current process        if (cpid == 0) // if child        {            close(pipefd[1]); // close write-end of pipe, i'm not going use            while (read(pipefd[0], &buf, 1) > 0) // read while eof                write(1, &buf, 1);            write(1, "\n", 1);            close(pipefd[0]); // close read-end of pipe            exit(exit_success);        }        else // if parent        {            close(pipefd[0]); // close read-end of pipe, i'm not going use            write(pipefd[1], argv[1], strlen(argv[1])); // send content of argv[1] reader            close(pipefd[1]); // close write-end of pipe, sending eof reader            wait(null); // wait child process exit before same            exit(exit_success);        }        return 0;    } 

the code pretty self-explanatory:

  1. parent forks()
  2. child reads() pipe until eof
  3. parent writes() pipe closes() it
  4. datas have been shared, hooray!

from there can want; remember check return values , read dup, pipe, fork, wait... manuals, come in handy.

there bunch of other ways share datas between processes, migh interest although not meet "private" requirement:

or simple file... (i've used sigusr1/2 signals send binary datas between processes once... wouldn't recommend haha.) , more i'm not thinking right now.

good luck.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

c# - Retrieve google contact -

javascript - How to insert selected radio button value into table cell -