在 Linux 上用 VS Code 编写 C 代码。
I use;
signal(SIGINT, myhandler);
signal(SIGHUP, myhandler);
signal(SIGKILL, myhandler);
signal(SIGTERM, myhandler);
我使用 VS 代码内部终端,选中“在终端中运行”选项。
当我的代码在循环中运行时,当我发送组合键 CTRL-C 时,执行会停止,但我的代码(myhandler)没有捕获信号。
我将“处理所有 nostop print pass”添加到 .gdbinit 文件中,但没有任何更改。
问题是如何捕获当前正在 VS Code 中调试的程序中从键盘发送的 CTRL-C (SIGINT)?
为了详细说明,我将添加我的 launch.json、tasks.json 和 main.c 文件,如下:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "gdb build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/bin/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: gcc build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc build active file",
"command": "/usr/bin/gcc",
"args": [
"-g",
"${workspaceFolder}/*.c",
"-o",
"${fileDirname}/bin/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"isDefault": true,
"kind": "build"
},
"detail": "compiler: /usr/bin/gcc"
}
]
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
// function prototypes
void initialize(void);
void sigHandler(int signo);
/*************** main routine which contains the infinite loop ****************/
int main(int argc, char *argv[])
{
initialize();
printf("It is alive...");
while (1)
{
// do something
printf("looping...");
usleep(10000);
}
return 0;
} //------------------------------- main -------------------------------------//
/**
* Let's get ready and initialize everything.
*/
void initialize(void)
{
signal(SIGINT, sigHandler);
signal(SIGHUP, sigHandler);
signal(SIGKILL, sigHandler);
signal(SIGTERM, sigHandler);
}
/**
* Stop before exiting and close everything.
*/
void sigHandler(int signo)
{
printf("Caught signal: %d, exiting!", signo);
exit(0);
}