如何在 C++ 中引发 SIGINT?
根据此 http://www.cplusplus.com/reference/clibrary/csignal /signal.html
SIGINT
通常由用户使用/引起。 如何在 C++ 中引发 SIGINT
? 我看到一个使用 kill(pid, SIGINT);
的示例,但我宁愿以另一种方式导致它。 我也在使用Windows。
According to this http://www.cplusplus.com/reference/clibrary/csignal/signal.html
SIGINT
is generally used/cause by the user. How do i cause a SIGINT
in c++? i seen an example using kill(pid, SIGINT);
but i rather cause it another way. Also i am using windows.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
C89和C99在signal.h中定义了raise():
该函数向调用进程发送信号,相当于
如果平台支持线程,则调用相当于
成功时返回值为0,否则为非零。
C89 and C99 define raise() in signal.h:
This function sends a signal to the calling process, and is equivalent to
If the platform supports threads, then the call is equivalent to
The return value is 0 on success, nonzero otherwise.
您可以通过按 Ctrl+C 来引发
SIGINT
。示例代码:
运行时:(
请注意,这是纯 C 代码,但应该在 C++ 中工作)
编辑:除了交互式地按 Ctrl+C< 之外,我知道发送
SIGINT
的唯一方法/kbd> 正在使用kill(pid, SIGINT)
正如你所说......You cause a
SIGINT
by pressing Ctrl+C.Example code:
When run:
(Note that this is pure C code, should work in C++ though)
Edit: The only way I know of to send
SIGINT
apart from interactively pressing Ctrl+C is usingkill(pid, SIGINT)
as you said...你还想什么办法?
kill()
函数是内核提供的以编程方式发送信号的唯一方法。实际上,您提到您正在使用 Windows。 我什至不确定
kill()
在 Windows 上做什么,因为 Windows 没有与 Unix 派生系统相同的信号架构。 Win32 确实提供了 TerminateProcess 函数,它可能会执行您想要的操作。 还有 GenerateConsoleCtrlEvent 函数,适用控制台程序并模拟 Ctrl+C 或 Ctrl+Break。What other way are you thinking of? The
kill()
function is the only way the kernel offers to programmatically send a signal.Actually, you mentioned you were using Windows. I'm not even sure what
kill()
does on Windows, since Windows doesn't have the same signal architecture that Unix-derived systems do. Win32 does offer the TerminateProcess function, which may do what you want. There is also the GenerateConsoleCtrlEvent function, which applies to console programs and simulates a Ctrl+C or Ctrl+Break.在这方面,“信号”是一个 Unix/POSIX 概念。 Windows 没有直接的等效项。
"Signals" in this regard are a Unix/POSIX concept. Windows has no direct equivalent.
我假设这是一个 Win32 应用程序...
对于“受控”或“安全”退出,如果应用程序使用消息循环,您可以从其内部使用 PostQuitMessage API,或在其外部使用 PostMessage。 否则,您将需要获取线程/进程 ID 并使用 TerminateThread 或 TerminateProcess API,具体取决于您是否只想终止一个线程或整个进程及其生成的所有线程。 Microsoft 在 MSDN 上对此进行了很好的解释(与所有 API 调用一样):
http: //msdn.microsoft.com/en-us/library/aa450927.aspx
I assume this is a Win32 app...
For a "controlled" or "safe" exit, if the app uses a message loop you can use the PostQuitMessage API from inside of it, or PostMessage outside of it. Otherwise you will need to get the thread/process ID and use the TerminateThread or TerminateProcess API, depending on if you want to kill just a thread or the entire process and all threads it has spawned. It is explained nicely by Microsoft (as with all API calls) on MSDN:
http://msdn.microsoft.com/en-us/library/aa450927.aspx