简体   繁体   中英

fork() Parent and child Processes of output

void main(){
  if(fork()==0)
    printf("a");
  else{
   printf("b");
   waitpid(-1,NULL,0);
}     
   printf("c");
   exit(0); 
}

Question: what is the output of the program?

a. acbc

b. bcac

c. abcc

d. bacc

e. A or C or D (Correct Answer)

So I am trying to figure out why C is one of corret answer.The following is my reasoning:

The child process go first then stop and pass control to the parent process, ('a' print out)

then parent process executes ("b" print out) because of waitpid(),

parent pass control back to child so in child process (c print out) and the child is reaped.

Finally, back to the parent process "c" print out. So we have abcc.

Am I right?

Theoretically, your answer is correct, it could happen like this (so at the end (a), (c), (d) seem they could happen).

Practically, the only correct answer is (a).

The reason for that is that stdio uses internally buffers for caching the output and avoiding expensive system calls. Therefore, until your program outputs `\\n' (newline) or exits, there is no output at all.

So the real scenario is going to be:

  1. child push character 'a' into buffer, then 'c' into buffer.
  2. parent simultaneously pushes character 'b' into buffer and waits for the child.
  3. child exits and flushes buffer containing "ac" before that.
  4. parent returns from waitpid() and pushes 'c' into buffer.
  5. parent exits and flushes buffer containing "bc" .

About the second part:

SIGKILL can kill any process (apart from some system processes). Child process is regular process like any other.

waitpid is to wait for child process until it exits. It has nothing to do with killing processes, it only waits (either due its own exit or due to being killed, no matter by which signal).

Your reasoning about how C could happen is correct. Timing (going down) would look something like this:

Parent    Child
          a
b
(waitpid)
          c
c

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