分叉,执行并杀死。僵尸进程
Fork, execlp and kill. Zombie process
我有一个 c 程序,它使用 fork 和 execlp 执行另一个进程(bash 脚本)。当我想终止这个进程时,它会进入僵尸状态。这是为什么??
创建进程:
switch (PID_BackUp= fork())
{
case -1:
perror("fork");
printf("An error has occurred launching backup.sh script!\n");
break;
case 0:
execlp("/usr/local/bin/backup.sh", "/usr/local/bin/backup.sh", NULL, NULL, NULL);
break;
default:
printf("backup.sh script launched correctly! PID: %d\n", PID_BackUp);
break;
}
终止一个进程:
if(kill(PID_BackUp,SIGKILL)==-1)
fprintf(stderr, "No se ha podido matar el programa: %d\n", PID_BackUp);
else
printf("\nProceso con identificador %d, se ha abortado\n", PID_BackUp);
所以此时进程进入僵尸状态。我做错了什么?
你应该打电话给 waitpid(2) or some other waiting system call (wait4(2)...) to avoid having zombie processes。顺便说一句,您还可以处理 SIGCHLD
信号,以便在子进程终止(或更改状态)时收到通知。
一般来说,你最好先kill(2) a process with SIGTERM
(and only later, with SIGKILL
) since that process -your backup.sh
script- could handle correctly (using trap
builtin in the shell script) the signal (but SIGKILL
cannot be caught, and the backup could e.g. leave clutter or useless files on the disk). See also signal(7) & signal-safety(7)
阅读Advanced Linux Programming(我们无法仅用几段文字解释那本免费提供的书的几章内容)。
顺便说一句,当系统调用失败时,最好在消息中使用 perror(3) 或 strerror(errno)
。
我有一个 c 程序,它使用 fork 和 execlp 执行另一个进程(bash 脚本)。当我想终止这个进程时,它会进入僵尸状态。这是为什么??
创建进程:
switch (PID_BackUp= fork())
{
case -1:
perror("fork");
printf("An error has occurred launching backup.sh script!\n");
break;
case 0:
execlp("/usr/local/bin/backup.sh", "/usr/local/bin/backup.sh", NULL, NULL, NULL);
break;
default:
printf("backup.sh script launched correctly! PID: %d\n", PID_BackUp);
break;
}
终止一个进程:
if(kill(PID_BackUp,SIGKILL)==-1)
fprintf(stderr, "No se ha podido matar el programa: %d\n", PID_BackUp);
else
printf("\nProceso con identificador %d, se ha abortado\n", PID_BackUp);
所以此时进程进入僵尸状态。我做错了什么?
你应该打电话给 waitpid(2) or some other waiting system call (wait4(2)...) to avoid having zombie processes。顺便说一句,您还可以处理 SIGCHLD
信号,以便在子进程终止(或更改状态)时收到通知。
一般来说,你最好先kill(2) a process with SIGTERM
(and only later, with SIGKILL
) since that process -your backup.sh
script- could handle correctly (using trap
builtin in the shell script) the signal (but SIGKILL
cannot be caught, and the backup could e.g. leave clutter or useless files on the disk). See also signal(7) & signal-safety(7)
阅读Advanced Linux Programming(我们无法仅用几段文字解释那本免费提供的书的几章内容)。
顺便说一句,当系统调用失败时,最好在消息中使用 perror(3) 或 strerror(errno)
。