Im quite new to C and am unsure how to proceed.
With this code I was attempting to create multiple child processes that would send their stdout to their parents stdin and have their stdin available to be written to with fdprintf of the pointer location in an array.
The code seems to not work, when executed with a basic program that reads stdin and prints to its stdout (which should be piped back). (In a different section of the main code I fprintf to where the pipe starts and then read stdin waiting for what should be written back).
int plumber(int *pipes[], int numChildren, char* command[]) {
int i;
char id;
int nullSpace = open("/dev/null", O_WRONLY);
for(i = 0; i < numChildren; ++i) {
id = 'A' + i;
pipe(pipes[2 * i]);
pipe(pipes[2 * i + 1]);
switch(fork()) {
case (-1):
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
break;
case 0:
//child
//close child's write, dupe its stdin to read
//close childs old read
close(pipes[2 * i][1]);
if(dup2(pipes[2 * i][0], 0) == -1) {
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
}
close(pipes[2 * i][0]);
//close child's read, dupe its stdout to write
//close childs old write
close(pipes[2 * i + 1][0]);
if(dup2(pipes[2 * i + 1][1], 1) == -1) {
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
}
close(pipes[2 * i + 1][1]);
close(1);
//child stderr to nullspace
if(dup2(nullSpace, 2) == -1) {
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
}
close(2);
execlp(command[i], "childprocess", numChildren, id, NULL);
break;
default:
//parent
//close read pipe from writing pipe
close(pipes[2 * i][0]);
//close write pipes and dupe stdin to read
//close parents old read
close(pipes[2 * i + 1][1]);
if(dup2(pipes[2 * i + 1][0], 0) == -1) {
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
}
close(pipes[2 * i + 1][0]);
}
}
close(nullSpace);
return 0;
}
The command is just to run the child process which also takes the number of children and an id from A to D. *pipes[] is numChildren*2 by 2 (so going along its child 1 read pipe, child1 write pipe, child2 read, child2 write etc. Please help and thanks in advance.