Hi, I have the following code that uses pipes to communicate. pipesIn is an array of pipes for the child processes to send messages to the parent process. When creating a child process, I duplicate the pipeIn write end to use stdout. But when writing to stdout using printf in the child process, the parent process doesn't get the message. What am I doing wrong?
Parent:
if (pid == 0) {
char* args = ""; // no arguments needed
close(pipesIn[0]); // close the read end of the pipe
dup2(pipesIn[1], STDOUT_FILENO); // create a pipe copy to stdout
close(pipesIn[1]); // close the write end of the pipe
execl("childProcess", args, NULL); // move into the child process
write_message("Error while executing child process");
exit(EXIT_FAILURE);
}
else { // we are in the parent thread
close(pipesIn[1]); // close the write end of the pipe
pids = pid;
char buffer [sizeof(int)*8+1];
sprintf(buffer, "%d", pids);
write_string("The child process was created with pid ", buffer);
char bufferIn[20];
ssize_t bytesRead = read(pipesIn[0], bufferIn, sizeof(bufferIn)); // read from the pipe
if (bytesRead == -1) { // didn't read anyting
write_message("Error when reading. Nothing was read");
exit(EXIT_FAILURE);
}
printf("Buffer in: %s\n", bufferIn); // print out what we got
wait(NULL);
}
Child process
int main(int argc, char* argv[]) {
char* test = "test";
printf("Running child process\n");
return 0;
}
Parent:
if (pid == 0) {
char* args = ""; // no arguments needed
close(pipesIn[0]); // close the read end of the pipe
dup2(pipesIn[1], STDOUT_FILENO); // create a pipe copy to stdout
close(pipesIn[1]); // close the write end of the pipe
execl("childProcess", args, NULL); // move into the child process
write_message("Error while executing child process");
exit(EXIT_FAILURE);
}
else { // we are in the parent thread
close(pipesIn[1]); // close the write end of the pipe
pids = pid;
char buffer [sizeof(int)*8+1];
sprintf(buffer, "%d", pids);
write_string("The child process was created with pid ", buffer);
char bufferIn[20];
ssize_t bytesRead = read(pipesIn[0], bufferIn, sizeof(bufferIn)); // read from the pipe
if (bytesRead == -1) { // didn't read anyting
write_message("Error when reading. Nothing was read");
exit(EXIT_FAILURE);
}
printf("Buffer in: %s\n", bufferIn); // print out what we got
wait(NULL);
}
Child process
int main(int argc, char* argv[]) {
char* test = "test";
printf("Running child process\n");
return 0;
}