简体   繁体   中英

Unpredictable output in simple fork program

Pardon me community for asking such a silly question - I've already spent 5+ hours trying to figure out reason but I've failed.

Below is the code, it was a question on our exam - we were asked if we can predict the output of this code and will it be definite?

After running this code on several machines, I've observed that output everywhere is - " child parent" .

My understanding of below code is that once the process has forked, a copy of process will be created which can only execute the statements which are written below the fork() call only. Now once fork() is done, there will be two processes - a child process & parent process . ( we've been instructed in our school that first parent process terminates and then child process when we are using pipes, however on searching internet I can only see that it cannot be decided which runs first.

Here is what I think should happen -

Scenario 1 - Child executes first

I think that when child executes first, it will first print "child", then write to file descriptor and then child process terminates due to _exit(0) and then parent process proceeds, reads and prints Parent. This is what is happening. I don't know whether this is actually happening or not.

Scenario 2 : Parent is executed first,

now it's attempting to first read empty pipe. Parent will try to read data, get blocked, then child will first print child, then write to pipe, which will enable read command and hence parent will be printed after it.

Can someone confirm if my understanding is correct and point out mistakes in my understanding..

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int BUFSIZE = 4096;
int main (int argc, char* argv[])
 {   int fd[2];
     pid_t pid;
     char buffer[BUFSIZE];
     pipe(fd);
     if ((pid = fork()) == 0)
    {   printf("child\n");
    write(fd[1], "a", 1);
     _exit(0);
     }
    read(fd[0], buffer, BUFSIZE);
    printf("parent\n");
     }

In your program, you have a pipe. The parent reads from one head of the pipe, and therefore he waits till someone writes on the other head of the pipe. The child writes, so even if parent was to execute first, he would wait for child to write. Change this:

read(fd[0], buffer, BUFSIZE);
printf("parent\n");

to

printf("parent\n");
read(fd[0], buffer, BUFSIZE);

and rerun it. Now it will print before trying to read. Even so, from time to time, it may be the child the first who prints, and sometimes will be the parent. It all depends who gets the processor first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM