使用SIGINT

2 c++ windows signals

根据这个http://www.cplusplus.com/reference/clibrary/csignal/signal.html

SIGINT通常由用户使用/导致.我如何SIGINT在c ++中导致?我看到一个使用的例子,kill(pid, SIGINT);但我宁愿以另一种方式引起它.我也在使用Windows.

Joa*_*lva 7

C89和C99在signal.h中定义raise():

#include <signal.h>

int raise(int sig);
Run Code Online (Sandbox Code Playgroud)

此函数向调用进程发送信号,相当于

kill(getpid(), sig);
Run Code Online (Sandbox Code Playgroud)

如果平台支持线程,则调用等效于

pthread_kill(pthread_self(), sig);
Run Code Online (Sandbox Code Playgroud)

成功时返回值为0,否则返回非零值.


Jon*_*Jon 5

SIGINT按下了原因Ctrl+C.

示例代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

运行时:

$ ./a.out 
^CUser pressed Ctrl+C
$ 
Run Code Online (Sandbox Code Playgroud)

(注意,这是纯C代码,但应该在C++中工作)

编辑:我所知道的唯一一种SIGINT从交互式按压发送的方式Ctrl+C就是kill(pid, SIGINT)按照你的说法使用...