Reputation: 3057
I have a program that creates multiple child processes using fork()
. The program starts in main of parent.c. After forking, the parent calls excel
to execute child.c. How exactly do I share a pipe between the two different programs. I know I would have to create a pipe in parent.c for each child process like this:
int myPipe[nChildren][2];
int i;
for (i = 0; i < nChildren; i++) {
if (pipe(myPipe[i]) == -1) {
perror("pipe error\n");
exit(1);
}
close(pipe[i][0]); // parent does not need to read
}
But what do I need to do in child.c?
Upvotes: 0
Views: 2227
Reputation: 3484
The child process needs to communicate the pipe FD to the execl
'ed program. The easiest way is to use dup2
to move the pipe to FD 0 (stdin
).
For example:
pid = fork();
if (pid == 0) {
// in child
dup2(pipe[i][0], 0);
execl(...);
}
Alternatively, you could use a command-line argument in child.c to accept the FD number of the pipe. for example:
pid = fork();
if (pid == 0) {
// in child
sprintf(pipenum, "%d", pipe[i][0]);
execl("child", "child", pipenum, (char *) NULL);
}
The child program would need to use atoi
or strtoul
to convert argv[1]
to an integer and then use that as the input FD.
Upvotes: 2