叉,execlp和杀死.僵尸进程 [英] Fork, execlp and kill. Zombie process
问题描述
我有一个C程序,使用fork和execlp执行另一个进程(bash脚本).当我想终止此过程时,它会进入僵尸状态.为什么会这样?
I have a c program that executes another process (bash script) with fork and execlp. When I want to kill this process it moves to a zombiee state. Why is this??
创建过程:
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);
因此,在这一点上,过程将进入僵尸状态.我在做什么错了?
So at this point the process moves to a zombie state. What I am doing wrong?
推荐答案
您应致电 wait4(2) ...)以避免僵尸进程 .顺便说一句,您也可以处理SIGCHLD
信号,以在子进程终止(或更改状态)时得到通知.
You should call waitpid(2) or some other waiting system call (wait4(2)...) to avoid having zombie processes. BTW you may also handle the SIGCHLD
signal to be notified when a child process has terminated (or changed state).
通常,最好先 kill(2)使用SIGTERM
的进程(并且以后才使用SIGKILL
),因为该进程-您的backup.sh
脚本-可以正确处理信号(使用shell脚本中内置的trap
),但是信号(但是SIGKILL
被捕获,备份可能会在磁盘上留下混乱或无用的文件).另请参见 signal(7)& 信号安全(7)
Generally, you'll better first 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)
阅读 高级Linux编程 (我们无法解释该课程的内容可在几章中的几章中免费获得这本书).
Read Advanced Linux Programming (we can't explain what is taught by that freely available book in several chapters in only a few paragraphs).
顺便说一句,最好使用 perror(3)或当系统调用失败时,在消息中显示strerror(errno)
.
BTW, better use perror(3) or strerror(errno)
in messages when a system call fails.
这篇关于叉,execlp和杀死.僵尸进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!