Communicating between processes

Joined
May 14, 2023
Messages
1
Reaction score
0
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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top