You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS Code停止调试模式时执行指定命令?

在VS Code中修改GDB调试停止时的默认终止操作

我在VS Code中通过launch请求方式使用GDB调试程序。

调试图标停止按钮

点击停止调试按钮时,VS Code默认会执行kill -s SIGKILL强制终止程序,但我希望在停止调试时执行自定义命令,能否通过修改launch.json实现?

注意:我已经了解postDebugTask配置,但它是在程序被终止之后运行额外任务,并非在停止调试时替换默认的终止操作,我需要修改的是停止程序时的默认行为。

我的launch.json内容如下:

{
    "name": "(gdb) Launch Nginx",
    "type": "cppdbg",
    "request": "launch",
    "program": "/usr/local/nginx/sbin/nginx",
    "args": [],
    "stopAtEntry": true,
    "cwd": "${fileDirname}",
    "environment": [],
    "externalConsole": false,
    "MIMode": "gdb",
    "setupCommands": [
        {
            "description": "Enable pretty-printing for gdb",
            "text": "-enable-pretty-printing",
            "ignoreFailures": true
        },
        {
            "description": "Set Disassembly Flavor to Intel",
            "text": "-gdb-set disassembly-flavor intel",
            "ignoreFailures": true
        }
    ]
}

可以通过在launch.json中添加terminateCommands配置项实现,该配置允许你自定义停止调试时发送给GDB的命令,替换默认的SIGKILL终止行为。

具体配置步骤:

  1. 在你的launch.json配置对象中添加terminateCommands数组,填写需要执行的GDB命令。
  2. 以Nginx优雅停止为例(发送SIGQUIT信号),修改后的配置如下:
{
    "name": "(gdb) Launch Nginx",
    "type": "cppdbg",
    "request": "launch",
    "program": "/usr/local/nginx/sbin/nginx",
    "args": [],
    "stopAtEntry": true,
    "cwd": "${fileDirname}",
    "environment": [],
    "externalConsole": false,
    "MIMode": "gdb",
    "setupCommands": [
        {
            "description": "Enable pretty-printing for gdb",
            "text": "-enable-pretty-printing",
            "ignoreFailures": true
        },
        {
            "description": "Set Disassembly Flavor to Intel",
            "text": "-gdb-set disassembly-flavor intel",
            "ignoreFailures": true
        }
    ],
    "terminateCommands": [
        "signal SIGQUIT"
    ]
}

说明:

  • terminateCommands中的命令会在点击停止调试按钮时,由GDB按顺序执行,完全替代默认的强制终止逻辑。
  • 可根据需求添加多条命令,比如先执行清理操作再终止程序,只需在数组中依次写入合法的GDB指令即可。
  • 确保使用GDB支持的命令格式,比如发送信号用signal <信号名/编号>,或调用程序内置的退出函数等。

内容的提问来源于stack exchange,提问作者hartvon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:53:16