我可以杀死进程本身吗?
我有一些在进程被终止时执行的代码,我实际上可以调用 kill(getpid())
来强制执行此代码(并明显关闭进程)吗?
I have some code that is executed when the process is killed, can I actually call kill(getpid())
to force the execution of this code (and close the process obviously)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,你可以。甚至还有一个特定的函数 -
raise(sig)
— 尽管kill(getpid(), sig)
也可以工作。Yes, you can. There's even a specific function for it —
raise(sig)
— althoughkill(getpid(), sig)
will work too.你可以使用kill来调用你自己的进程:
有关详细信息,请参阅 kill()、getpid(), 信号
you can call your own process using kill through:
For more information see kill(), getpid(), SIGINT
尝试
exit
- 简单多了 - 为什么让事情变得复杂?Try
exit
- a lot simpler - why make things complicated?我怀疑你的设计选择存在更大的问题。
如果您想在进程终止时执行某些代码,请使用
atexit
注册该代码。也就是说,是的,您可以使用
kill(getpid(), sig) 向自己的进程发送信号。
I suspect there's a larger problem with your design choices.
If you want to execute some code when your process terminates, register the code with
atexit
.That said, yes, you can send your own process a signal with
kill(getpid(), sig)
.您可以使用kill(getpid(), SIGSPEC) 正确执行此操作,以执行实际安装为SIGSPEC 指定的任何特定信号的信号处理程序的代码。
当然,您不能捕获 SIGKILL 或 SIGSTOP ,因为它们没有处理程序。所有其他信号都可以使用信号代码安装处理程序。
如果处理程序代码不是信号处理程序而是 atexit 处理程序,则只能通过 exit() 调用来调用它。请注意,_exit() 调用会绕过所有 atexit 处理程序。
我还在这里看到一些评论,似乎表明kill(getpid(), SIGSPEC) 与_exit() 或exit() 相同,但事实并非如此!它们是不同的东西。
我的建议是阅读 exit(3) _exit(2) signal(7) signal(2) raise(3) sigaction(3) 手册页以获得完整的理解。
You can use kill(getpid(), SIGSPEC) to do this properly to execute the code that's actually installed as a signal handler for any particular signal specified by SIGSPEC.
You cannot of course capture SIGKILL or SIGSTOP those cannot have handlers. All other signals can have handlers installed using the signal code.
If the handler code is not a signal handler but an atexit handler then it will only be called via exit() call. Note that _exit() call bypasses all atexit handlers.
Also i see a few comments here that seem to suggest that kill(getpid(), SIGSPEC) is the same as _exit() or exit() IT IS NOT! They are different things.
My suggestion would be to read exit(3) _exit(2) signal(7) signal(2) raise(3) sigaction(3) man pages for a complete understanding.
进程可以通过以下方式杀死自己:
杀死(getpid(),SIGKILL);
A process can kill itself in a following way:
kill(getpid(), SIGKILL);