KILL信号会立即退出进程吗? [英] Does a KILL signal exit a process immediately?

查看:78
本文介绍了KILL信号会立即退出进程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理使用 fork()和exec创建子进程的服务器代码.当 fork()成功时,将注册该子项的PID,并在捕获到 CHILD 信号时清除该子项的PID.

I'm working on a server code that uses fork() and exec to create child processes. The PID of the child is registered when fork() succeeds and cleaned up when the CHILD signal has been caught.

如果服务器需要停止,则所有程序都将被杀死,并最终发出KILL信号.现在,通过遍历所有已注册的PID并等待CHILD信号处理程序删除PID来工作.如果子程序未正确退出,则此操作将失败.因此,我想将 kill waitpid 结合使用,以确保清除PID列表并记录日志,否则进行其他操作.

If the server needs to stop, all programs are killed, eventually with a KILL signal. Now, this works by means of iterating through all registered PIDs and waiting for the CHILD signal handler to remove the PIDs. This will fail if child program did not exit properly. Therefore I want to use kill in combination with waitpid to ensure that PID list is cleaned up and log and do some other stuff otherwise.

考虑下一个代码示例:

kill(pid, SIGKILL);
waitpid(pid, NULL, WNOHANG);

摘录自 waitpid(2):

waitpid():成功后,返回状态已更改的子进程的ID.如果指定了WNOHANG,并且有一个或多个孩子由pid指定的存在,但尚未更改状态,则返回0.如果出错,则返回-1.

waitpid(): on success, returns the process ID of the child whose state has changed; if WNOHANG was specified and one or more child(ren) specified by pid exist, but have not yet changed state, then 0 is returned. On error, -1 is returned.

pid 给出的过程是否总是在下一个函数启动之前就消失了?在上述情况下, waitpid 是否总是返回 -1 吗?

Is the process given by pid always gone before the next function kicks in? Will waitpid always return -1 in the above case?

推荐答案

在下一个函数启动之前,pid给定的过程是否总是消失了?

Is the process given by pid always gone before the next function kicks in?

对此不做任何保证.在多处理器上,您的进程可能在CPU 0上,而内核中被杀死的进程的清理在CPU 1上进行.这是经典的竞争条件.即使在单核处理器上也无法保证.

There is no guarantee for that. On a multiprocessor your process might be on CPU 0 while the cleanup in the kernel for the killed process takes place on CPU 1. That's a classical race-condition. Even on singlecore processors there is no guarantee for that.

在上述情况下,waitpid是否总是返回-1?

Will waitpid always return -1 in the above case?

由于这是比赛条件-在大多数情况下,可能会.但是并不能保证.

Since it is a race condition - in most cases it perhaps will. But there is no guarantee.

由于您对状态不感兴趣,因此此半代码可能更适合您的情况:

Since you are not interested in the status, this semicode might be more appropriate in your case:

// kill all childs
foreach(pid from pidlist)
    kill(pid, SIGKILL);

// gather results - remove zombies
while( not_empty(pidlist) )
    pid = waitpid(-1, NULL, WNOHANG);
    if( pid > 0 )
        remove_list_item(pidlist, pid);
    else if( pid == 0 )
        sleep(1);
    else
        break;

这篇关于KILL信号会立即退出进程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆