可以在调用 kill 函数之前编程 return/terminate 吗?

Can program return/terminate before the kill function is called?

我对 kill(pid, signal) 函数的工作原理有点困惑 - 我认为它是异步的,因此在执行更多指令后信号可能不会到达。我的问题是,如果您在下一行调用 kill(pid, signal) 然后调用 return (如下所示),您是否保证在程序终止之前捕获并处理信号,或者是否有可能如果我们 运行 "return 0" 在 kill 函数完成之前退出而不处理信号?

kill(pid, SIGUSR1);
return 0;

如果一个进程只向自己发送一个信号,并且该信号没有被阻塞,并且该进程没有其他未决信号,那么该信号将被同步发送(即,在 kill() 之前returns).

这不足以保证 100% 可靠,因此您可能不想依赖它。例如,另一个进程可能恰好在同一时间发送不同的信号;那可能不在您的控制范围内。

如果一个进程向另一个进程发送信号,则无法保证在 kill() return 秒之前收到信号。但是即使信令功能终止,它也会被发送。

如果有多个进程会收到信号,kill可能会在第一个信号发送后return,不保证一定是信号进程。同样,这可能会导致在接收到信号之前进行 returning 处理。一些平台可能会提供额外的保证。

这是 Posix specification:

If the value of pid causes sig to be generated for the sending process, and if sig is not blocked for the calling thread and if no other thread has sig unblocked or is waiting in a sigwait() function for sig, either sig or at least one pending unblocked signal shall be delivered to the sending thread before kill() returns.