Using SIGINT

According to this http://www.cplusplus.com/reference/clibrary/csignal/signal.html

SIGINT commonly used / calls the user. How to call SIGINT in C ++? I saw an example using kill(pid, SIGINT); but I would rather explain it in a different way. I also use windows.

+2
source share
6 answers

C89 and C99 define raise () in signal.h:

 #include <signal.h> int raise(int sig); 

This function sends a signal to the calling process and is equivalent to

 kill(getpid(), sig); 

If the platform supports threads, then the call is equivalent

 pthread_kill(pthread_self(), sig); 

The return value is 0 if successful, other than zero.

+7
source

You call SIGINT by pressing Ctrl + C.

Code example:

 #include <stdio.h> #include <stdlib.h> #include <signal.h> void siginthandler(int param) { printf("User pressed Ctrl+C\n"); exit(1); } int main() { signal(SIGINT, siginthandler); while(1); return 0; } 

At startup:

 $ ./a.out ^CUser pressed Ctrl+C $ 

(Note that this is pure C code, should work in C ++, though)

Edit: the only way I know to send SIGINT , besides interactively pressing Ctrl + C , uses kill(pid, SIGINT) , as you said ...

+5
source

What other way do you think? The kill() function is the only way the kernel programmatically sends a signal.

Actually, you mentioned that you are using Windows. I'm not even sure what kill() does for Windows, since Windows does not have the same signal architecture as on Unix-derived systems. Win32 offers a TerminateProcess function that can do what you want. There is also a GenerateConsoleCtrlEvent function that applies to console programs and mimics Ctrl + C or Ctrl + Break.

+1
source

β€œSignals” in this regard is a Unix / POSIX concept. Windows does not have a direct equivalent.

+1
source

I assume this is a Win32 application ...

For a β€œcontrolled” or β€œsafe” exit, if the application uses a message loop, you can use the PostQuitMessage API from within or PostMessage outside. Otherwise, you will need to get the thread / process identifier and use the TerminateThread or TerminateProcess API, depending on whether you want to kill only the thread or the whole process and all the threads that it spawned. This is well explained by Microsoft (as with all API calls) on MSDN:

http://msdn.microsoft.com/en-us/library/aa450927.aspx

0
source
  void SendSIGINT( HANDLE hProcess ) { DWORD pid = GetProcessId(hProcess); FreeConsole(); if (AttachConsole(pid)) { // Disable Ctrl-C handling for our program SetConsoleCtrlHandler(NULL, true); GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // SIGINT //Re-enable Ctrl-C handling or any subsequently started //programs will inherit the disabled state. SetConsoleCtrlHandler(NULL, false); WaitForSingleObject(hProcess, 10000); } } 
0
source

Source: https://habr.com/ru/post/895565/


All Articles