2
votes

If a parent has two child processes and each child has its own pipe, how can the parent write to the pipes of each of its child processes? Is there any way to call a function where a process can specify a particular child's id?

1
No. You have to couple a pid with a fd-pair (pipe) yourself. (And don't forget that each process should close all the pipe file descriptors it doesn't use or else you'll have problems won't get EOFs where you need them). - PSkocik
I totally get your point but I am still confused about coupling the pid with fd-pair. How do you do that? Because what I am doing is that i create a child process, check the output of fork() using if-else statements, if there's parent, I create another child process and repeat the same if-else statements. Then if it's parent process, I receive messages from server. What I want to do here is that I want to send the received messages at the parent process to children process, based on some basic conditions. - moirK

1 Answers

1
votes

Before you fork, create a pipe (fd pair).

int pipe_fds[2];
if(0>pipe(pipe_fds[2])) /*handle err.*/;

fork, and then have the parent process close the read end and save the write end of the pipe into a pid_to_pipe table:

if(0>(pid = fork())) /*handle err.*/;

if(pid){ //parent
     if(0>save_pid_to_pipe(pid, pipe_fds[1])) /*handle err.*/;
     close(pipe_fds[0]);
}

The child needs to close the write end of the latest pipe:

close(pipe_fds[0]);

and all the write ends in the parent's lookup table. Then it can wait on instructions on pipe_fds[0]; (the read end that was the latest read end at the time the child was created), while the parent can choose the corresponding write end by pid via the lookup table.

You can use a simple array, a sorted array, a map, or a hash for the lookup table.