【发布时间】:2021-06-03 19:05:34
【问题描述】:
我编写了这个简单的程序,它无休止地要求用户输入,然后使用 fork() 创建另一个进程来执行“ls -la”。
当用户输入为0时,进程被创建为后台进程。如果用户输入的是其他内容,则父进程等待子进程终止。
在每次迭代中,僵尸进程都会终止。这似乎工作得很好
这段代码的问题是:创建后台进程时,任何后续进程的父进程都不再等待。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
void delete_zombies(void)
{
pid_t kidpid;
int status;
while ((kidpid = waitpid(-1, &status, WNOHANG)) > 0)
{
printf("Child %ld terminated\n", kidpid);
}
}
int main() {
int runBGflag =0;
while(1)
{
scanf("%d",&runBGflag); //get user input
if (runBGflag==0) printf("making a child process and wait for it to finish\n");
else printf("making a background process\n");
pid_t pid; //fork
pid = fork();
if (pid > 0 && runBGflag==0) //Parent process. Waits for child termination and prints exit status
{
int status;
if (waitpid(-1, &status, 0) == pid && WIFEXITED(status))
{
printf("child dead. parent continues\n");
}
}
if (pid == 0) //Child process. Executes commands and prints error if something unexpected happened
{
execlp ("ls", "-la", NULL);
printf ("exec: %s\n", strerror(errno));
exit(1);
}
delete_zombies();
}
}
我期待输出
例如我希望输入 010 后有以下输出
0
making a child process and wait for it to finish
CMakeCache.txt cmake_install.cmake sigchild Testing
CMakeFiles Makefile sigchild.cbp
child dead. parent continues
1
making a background process
CMakeCache.txt cmake_install.cmake sigchild Testing
CMakeFiles Makefile sigchild.cbp
0
making a child process and wait for it to finish
CMakeCache.txt cmake_install.cmake sigchild Testing
CMakeFiles Makefile sigchild.cbp
child dead. parent continues
但是我只得到
0
making a child process and wait for it to finish
CMakeCache.txt cmake_install.cmake sigchild Testing
CMakeFiles Makefile sigchild.cbp
child dead. parent continues
1
making a background process
CMakeCache.txt cmake_install.cmake sigchild Testing
CMakeFiles Makefile sigchild.cbp
0
making a child process and wait for it to finish
CMakeCache.txt cmake_install.cmake sigchild Testing
CMakeFiles Makefile sigchild.cbp
【问题讨论】: