C语言 我可以自行终止进程吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7851121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:57:26  来源:igfitidea点击:

Can I kill a process from itself?

cunixprocess

提问by Francesco Belladonna

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)?

我有一些在进程被终止时执行的代码,我实际上可以调用kill(getpid())强制执行此代码(并明显关闭进程)吗?

回答by Ilmari Karonen

Yes, you can. There's even a specific function for it — raise(sig)— although kill(getpid(), sig)will work too.

是的你可以。它甚至有一个特定的功能raise(sig)——尽管它也kill(getpid(), sig)可以工作。

回答by Daniel

you can call your own process using kill through:

您可以通过以下方式使用 kill 调用您自己的进程:

kill(getpid(),SIGINT);

For more information take a look at this

有关更多信息,请查看

This would have a similar effect to exit() command.

这将具有与 exit() 命令类似的效果。

回答by Ed Heal

Try exit- a lot simpler - why make things complicated?

尝试exit- 简单得多 - 为什么要把事情复杂化?

回答by tdenniston

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.

如果要在进程终止时执行某些代码,请使用atexit.

That said, yes, you can send your own process a signal with kill(getpid(), sig).

也就是说,是的,您可以使用kill(getpid(), sig).

回答by Ahmed Masud

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.

您可以使用 kill(getpid(), SIGSPEC) 正确执行此操作,以执行实际安装为 SIGSPEC 指定的任何特定信号的信号处理程序的代码。

You cannot of course capture SIGKILL or SIGSTOP those cannot have handlers. All other signals can have handlers installed using the signal code.

您当然不能捕获那些不能有处理程序的 SIGKILL 或 SIGSTOP 。所有其他信号都可以使用信号代码安装处理程序。

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.

如果处理程序代码不是信号处理程序而是 atexit 处理程序,那么它只能通过 exit() 调用来调用。请注意,_exit() 调用会绕过所有 atexit 处理程序。

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.

此外,我在这里看到一些评论似乎表明 kill(getpid(), SIGSPEC) 与 _exit() 或 exit() 相同,这不是!它们是不同的东西。

My suggestion would be to read exit(3) _exit(2) signal(7) signal(2) raise(3) sigaction(3) man pages for a complete understanding.

我的建议是阅读 exit(3) _exit(2) signal(7) signal(2) raise(3) sigaction(3) 手册页以获得完整的理解。

回答by ivan.ukr

A process can kill itself in a following way: kill(getpid(), SIGKILL);

进程可以通过以下方式杀死自己:kill(getpid(), SIGKILL);