我知道waitpid()是用来等待进程完成的,但是该如何使用它呢?
这里我想做的是,创建两个孩子,等待第一个孩子完成,然后在退出之前杀死第二个孩子。
//Create two children
pid_t child1;
pid_t child2;
child1 = fork();
//wait for child1 to finish, then kill child2
waitpid() ... child1 {
kill(child2) }发布于 2014-01-21 12:17:28
waitpid()的语法
pid_t waitpid(pid_t pid, int *status, int options);pid的值可以是:
pid.pid.值的子进程
options的值是以下零个或多个常量的OR:
如果没有子级,则立即返回
WNOHANG:;如果子级已停止,则立即返回exited.WUNTRACED:。即使此选项不是specified.WCONTINUED:,也会提供已停止的被跟踪子项的状态。如果已停止的子项已通过SIGCONT.的传送恢复,也会返回
要获得更多帮助,请使用man waitpid。
发布于 2014-01-21 13:18:07
语法是
pid_t waitpid(pid_t pid, int *statusPtr, int options);1.其中pid是它应该等待的子进程。
2.statusPtr是指向存储终止进程的状态信息的位置的指针。
3.为waitpid函数指定可选操作。可以指定以下任一选项标志,也可以将它们与按位包含or运算符组合使用:
WNOHANG WUNTRACED
如果成功,waitpid将返回已上报状态的已终止进程的进程ID。如果不成功,则返回-1。
等待带来的好处
1.如果进程有多个子进程,并且希望在父进程恢复之前等待特定的子进程完成执行,则可以使用1.Waitpid
2. 2.waitpid支持作业控制
3.支持父进程的非阻塞
发布于 2019-05-21 19:56:40
#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;
}https://stackoverflow.com/questions/21248840
复制相似问题