[英]C- Reaping Child Process and Background
pid_t pid;
if ((pid == fork()) == 0){
if (execvp(arg[0], arg) < 0) {
printf("%s: Command not found.\n", arg[0]);
exit(0);
}
}
if (background == 0 )
{
int status;
if (waitpid(pid, &status, 0) < 0)
printf("waitfg: waitpid error");
while(waitpid(-1, 0, WNOHANG) >= 0){}
}
else
{
printf("%d %s", pid, cmdline);
}
I have this code for my program and I am trying to have the parent reap all child processes and the problem is that it is still not reaping.我的程序有这个代码,我试图让父进程收割所有子进程,但问题是它仍然没有收割。 I am trying to use the code:我正在尝试使用以下代码:
while(waitpid(-1, 0, WNOHANG) >= 0){}
in order to reap but it seems to not get rid of the zombie process.为了收获却似乎没有摆脱僵尸进程。 What am I supposed to do to reap instead then我该怎么做才能收获呢
Also I am not sure if I am doing background right here.我也不确定我是否在这里做背景。
Your code is wrong:你的代码是错误的:
pid_t pid;
if ((pid == fork()) == 0){ // PROBLEM HERE
if (execvp(arg[0], arg) < 0) {
printf("%s: Command not found.\n", arg[0]);
exit(0);
}
}
you compare pid
which isn't initialized with result of fork()
=> Undefined behavior (and after, you compare the result of this comparison with 0)您比较未用fork()
=> 未定义行为的结果初始化的pid
(然后,您将此比较的结果与 0 进行比较)
You should replace if ((pid == fork()) == 0){
by if ((pid = fork()) == 0){
您应该将if ((pid == fork()) == 0){
替换为if ((pid = fork()) == 0){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.