我知道waitpid()
用于等待进程完成,但是如何才能完全使用它?
这里我要做的是,创建两个孩子并等待第一个孩子完成,然后在退出前杀死第二个孩子。
//Create two children
pid_t child1;
pid_t child2;
child1 = fork();
//wait for child1 to finish, then kill child2
waitpid() ... child1 {
kill(child2) }
答案 0 :(得分:23)
waitpid()
的语法:
pid_t waitpid(pid_t pid, int *status, int options);
pid
的值可以是:
pid
绝对值的任何子进程。pid
。options的值是以下常量中零或更多的OR:
WNOHANG
:如果没有孩子退出,请立即返回。WUNTRACED
:如果孩子已经停止,也会返回。即使未指定此选项,也会提供已停止的已跟踪子项的状态。WCONTINUED
:如果已通过递送SIGCONT
恢复已停止的孩子,也会返回。如需更多帮助,请使用man waitpid
。
答案 1 :(得分:13)
语法是
pid_t waitpid(pid_t pid, int *statusPtr, int options);
1.其中pid是孩子应该等待的过程。
2.statusPtr是指向要存储终止进程的状态信息的位置的指针。
3.指定waitpid函数的可选操作。可以指定以下任一选项标志,也可以将它们与按位包含的OR运算符组合使用:
<强> WNOHANG WUNTRACED WCONTINUED 强>
如果成功,waitpid将返回已报告其状态的已终止进程的进程ID。如果不成功,则返回-1。
等待的好处
1.Waitpid可以在您有多个子进程时使用,并且您希望等待特定的子进程在父进程恢复之前完成执行
2.waitpid支持作业控制
3.it支持非阻止父进程
答案 2 :(得分:-2)
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main (){
int pid;
int status;
printf("Parent: %d\n", getpid());
pid = fork();
if (pid == 0){
printf("Child %d\n", getpid());
sleep(2);
exit(EXIT_SUCCESS);
}
//Comment from here to...
//Parent waits process pid (child)
waitpid(pid, &status, 0);
//Option is 0 since I check it later
if (WIFSIGNALED(status)){
printf("Error\n");
}
else if (WEXITSTATUS(status)){
printf("Exited Normally\n");
}
//To Here and see the difference
printf("Parent: %d\n", getpid());
return 0;
}