简体   繁体   English

KILL信号是否立即退出进程?

[英]Does a KILL signal exit a process immediately?

I'm working on a server code that uses fork() and exec to create child processes. 我正在使用fork()和exec来创建子进程的服务器代码。 The PID of the child is registered when fork() succeeds and cleaned up when the CHILD signal has been caught. fork()成功时注册子项的PID,并在捕获CHILD信号时清除子项的PID。

If the server needs to stop, all programs are killed, eventually with a KILL signal. 如果服务器需要停止,所有程序都会被终止,最终会有一个KILL信号。 Now, this works by means of iterating through all registered PIDs and waiting for the CHILD signal handler to remove the PIDs. 现在,这通过迭代所有已注册的PID并等待CHILD信号处理程序移除PID来工作。 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. 因此,我希望将killwaitpid结合使用以确保清除PID列表并记录并执行其他一些其他操作。

Consider the next code sample: 考虑下一个代码示例:

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

Excerpt from waitpid(2) : 摘自waitpid(2)

waitpid(): on success, returns the process ID of the child whose state has changed; waitpid():成功时,返回状态已更改的子进程ID; if WNOHANG was specified and one or more child(ren) specified by pid exist, but have not yet changed state, then 0 is returned. 如果指定了WNOHANG并且存在由pid指定的一个或多个子(ren),但尚未更改状态,则返回0。 On error, -1 is returned. 出错时,返回-1。

Is the process given by pid always gone before the next function kicks in? 在下一个函数启动之前, pid给出的进程是否总是消失? Will waitpid always return -1 in the above case? 在上述情况下, waitpid总是返回-1

Is the process given by pid always gone before the next function kicks in? 在下一个函数启动之前,pid给出的进程是否总是消失?

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. 在多处理器上,您的进程可能在CPU 0上,而内核中针对被杀死进程的清理在CPU 1上进行。这是一个经典的竞争条件。 Even on singlecore processors there is no guarantee for that. 即使在单一处理器上也无法保证。

Will waitpid always return -1 in the above case? 在上述情况下,waitpid是否总是返回-1?

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;

The KILL signal handler will run during the killed processes CPU time. KILL信号处理程序将在被杀死的进程CPU时间内运行。 This is potentially much later than your waitpid call, especially on a loaded system, so waitpid can very well return 0. 这可能比waitpid调用晚得多,特别是在加载的系统上,所以waitpid可以很好地返回0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM