微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Ubuntu中的wait函数

我正在学习Ubuntu中的进程及其行为,但在wait()中有点困惑。 所以我的问题是:

如何将statment while(wait(NULL)> 0); 工作中?

wait()中的NULL的目的是什么?

我已经看到terminal中的输出,但是父母正在执行并且让孩子执行wait()函数。 父执行不应该停止? 这里是代码

int main(int argc,char *argv[]) { pid_t childid; if(argc!=2) { printf("Please provide an argument in terminal! n"); return 0; } int i,n=atoi(argv[1]); for(i=0;i<n;i++) { childid=fork(); if(childid==0) { printf("Inside Child process! n My id is %dn",getpid()); break; // creating fan process structure } else if(childid>0) { printf("Inside Parent Process! n My id is %dn",getpid()); } } while(wait(NULL)>0); printf("After While Statment!n My id is %dn My parent ID is %dn Child id is %dn",getpid(),getppid(),childid);

}

我知道这是一个非常蹩脚的问题,但这是人们学习的方式:)

实时追踪日志摘录

后执行脚本的命令

如何杀死僵尸进程使用wait()

有没有办法使PowerShell等待安装完成?

Waitpid块永远

谢谢

如何使主窗口等待,直到一个新打开的窗口closures在C#WPF中?

如何在Linux中高效地等待RS232的CTS或DSR?

如何使用linux`perf`工具来生成“Off-cpu”configuration文件

僵尸程序在父母去世之后在哪里?

为什么wait4()被waitpid()取代

如何将statment while(wait(NULL)> 0); 工作中?

函数wait ,等待任何子进程的终止,如果成功,则返回终止子进程的标识符。如果没有子进程,则返回-1。

在你的代码中,父进程基本上等待所有已经创建的子进程的终止。

对于任何一个孩子来说,这个调用将立即返回-1,因为他们还没有创建任何进程。

wait()中NULL的目的是什么 如果你看到等待的原型,就是这样,

pid_t wait(int *status);

父进程可以获取变量状态下的子进程的退出状态(我们需要传递wait函数中的整数地址,更新该整数),然后使用WEXITSTATUS宏来提取该值。

通过NULL(我们通过NULL,因为变量是指针类型)的意思是,程序员对这个值不感兴趣,他正在通知这个等待调用

我稍微修改了你的代码,解释了等待函数的返回值和使用非NULL参数。 所有的孩子现在正在返回一个值(循环索引我),这是由父母提取

PL。 看看这是否有帮助,

#include<stdio.h> #include<sys/types.h> #include<sys/wait.h> #include<stdlib.h> int main(int argc,char *argv[]) { pid_t childid; int ret; int status; if(argc!=2) { printf("Please provide an argument in terminal! n"); return 0; } int i,n=atoi(argv[1]); for(i=0;i<n;i++) { childid=fork(); if(childid==0){ printf("Inside Child process! n My id is %dn",getpid()); break; // creating fan process structure } else if(childid > 0){ printf("Inside Parent Process! n My id is %dn",getpid()); } } //The line below,will be immediatly false for all the children while ((ret= wait(&status))>0) { printf("After While My id is %d and my child with pid =%d exiting with return value=%dn",ret,WEXITSTATUS(status)); } //The if below will be true for the children only if ((0 > ret) && (childid == 0)){ printf("Child with id %d exiting and my parent's id is %dn",getppid()); exit(i); } else{ printf("Parent Finally Exitingn"); } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐