简体   繁体   English

fork()父级和子级输出过程

[英]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. b。 bcac c

c. C。 abcc 密件抄送

d. d。 bacc 百家乐

e. e。 A or C or D (Correct Answer) A或C或D(正确答案)

So I am trying to figure out why C is one of corret answer.The following is my reasoning: 所以我想弄清楚为什么C是正确的答案之一。以下是我的推理:

The child process go first then stop and pass control to the parent process, ('a' print out) 子进程首先运行,然后停止并将控制权传递给父进程(“ a”打印输出)

then parent process executes ("b" print out) because of waitpid(), 然后由于waitpid(),父进程将执行(打印出“ b”),

parent pass control back to child so in child process (c print out) and the child is reaped. 父级将控制权传回给孩子,以便在子级处理(c打印输出)中获得子级。

Finally, back to the parent process "c" print out. 最后,回到父进程“ c”打印出来。 So we have abcc. 所以我们有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). 从理论上讲,您的答案是正确的,它可能会像这样发生(因此,在最后(a),(c),(d)看来它们可能会发生)。

Practically, the only correct answer is (a). 实际上,唯一正确的答案是(a)。

The reason for that is that stdio uses internally buffers for caching the output and avoiding expensive system calls. 原因是stdio使用内部缓冲区来缓存输出并避免昂贵的系统调用。 Therefore, until your program outputs `\\n' (newline) or exits, there is no output at all. 因此,在程序输出`\\ n'(换行符)或退出之前,根本没有输出。

So the real scenario is going to be: 因此,实际情况将是:

  1. child push character 'a' into buffer, then 'c' into buffer. 子级将字符'a'推入缓冲区,然后将'c'推入缓冲区。
  2. parent simultaneously pushes character 'b' into buffer and waits for the child. 父级同时将字符'b'压入缓冲区并等待子级。
  3. child exits and flushes buffer containing "ac" before that. 子级退出并刷新之前包含"ac"缓冲区。
  4. parent returns from waitpid() and pushes 'c' into buffer. 父级从waitpid()返回并将'c'压入缓冲区。
  5. parent exits and flushes buffer containing "bc" . 父级退出并刷新包含"bc"缓冲区。

About the second part: 关于第二部分:

SIGKILL can kill any process (apart from some system processes). SIGKILL可以终止任何进程(某些系统进程除外)。 Child process is regular process like any other. 子进程像其他进程一样是常规进程。

waitpid is to wait for child process until it exits. waitpid是等待子进程直到退出。 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. 您关于C如何发生的推理是正确的。 Timing (going down) would look something like this: 时间(下来)看起来像这样:

Parent    Child
          a
b
(waitpid)
          c
c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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