首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >进程ID,waitpid

进程ID,waitpid
EN

Stack Overflow用户
提问于 2012-12-10 06:39:42
回答 2查看 2.1K关注 0票数 0

以下代码:

代码语言:javascript
复制
B() { 
   pid_t pid; 
   if ((pid=fork())!= 0) 
       waitpid(pid,NULL,0); 
   printf("2 "); 
   if (fork() == 0) 
      { printf("3 "); exit(0); } 
   printf("5 "); 
   exit(0); 
}

可以有一个输出:我不确定哪一个是正确的输出。

代码语言:javascript
复制
232553
235325
232355
235253
252533

这两行意味着如果pid是父进程,那么等待什么?

代码语言:javascript
复制
if ((pid=fork())!= 0) 
           waitpid(pid,NULL,0); 

如果是子进程(fork = 0),则打印3..对,是这样?

代码语言:javascript
复制
 if (fork() == 0) 
              { printf("3 "); exit(0); }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-10 06:45:25

代码语言:javascript
复制
B() { 
   pid_t pid; 

   /* On success, fork() returns 0 to the child. It returns the child's process 
    * ID to the parent. So this block of code, executes a fork(), and has the
    * parent wait for the child.
    * Amusing sidenote: if the fork() fails, the parent will wait for *any* 
    * child process, since the return will be -1.
    */
   if ((pid=fork())!= 0) 
       waitpid(pid,NULL,0); 

   /* Both the parent and the child will print 2. The parent, will, of course,
    * only print 2 after the child exits, because of the waitpid above.
    */
   printf("2 "); 

   /* Now we fork again. Both the parent and the child from the previous fork will
    * fork again, although the parent will do it *after* the child exit. The resulting 
    * child process will print a single 3 and then exit.
    */
   if (fork() == 0) 
      { printf("3 "); exit(0); } 

   /* Now both the parent and the child print a 5 and exit */
   printf("5 "); 
   exit(0); 
}

正如David Schwartz所说,这个程序的输出将由数字2、3和5的某种排列组成。没有一个输出是正确的,因为输出取决于进程执行的顺序,这是任意的。

票数 5
EN

Stack Overflow用户

发布于 2012-12-10 06:43:37

waitpid函数等待该子进程终止。你说的其他一切都是对的。对于这样的程序,没有一个正确的输出,因为它取决于进程执行的顺序,这是任意的。

代码语言:javascript
复制
   if ((pid=fork())!= 0) 
       waitpid(pid,NULL,0); 

好的,现在父母将等待孩子终止。

代码语言:javascript
复制
   printf("2 "); 

子节点将立即输出2。父进程将在子进程终止后的一段时间输出2。

代码语言:javascript
复制
   if (fork() == 0) 
      { printf("3 "); exit(0); } 

父进程和子进程都将派生。他们的两个孩子都将打印3并退出。

代码语言:javascript
复制
   printf("5 "); 

父项和原始子项都将打印5。

代码语言:javascript
复制
   exit(0);

父级和原始子级都将刷新其输出缓冲区并终止。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13792631

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档