Search code examples
debuggingvisual-studio-codecompilation

VS Code debugging: Is it possible to supply process-id 'pgrep -x "$myprog"' for use in launch.json (variable "processId") when attach to process-id?


I noticed that for node.js there's a debugger "auto attach" feature, which I would like to use if it was possible. However, I don't think I can use "auto attach" to automatically fire up the debugger after I've re-compiled my program. I compile my program using C/C++/Fortran using makefiles (and similar) so after running "make" I get a normal (linux) executable. I then execute that binary and often want to debug it right away, after this. I have the full binary path set to an environment variable "$myprog=/home/user/my-dev/bin/myApp".

So what I do is to run debug using "Attach to process" and every time I have to find the proper process in the dropdown list, but I do it too many times each day, each hour, it's becoming tedious and would like something smarter, "more automatically":

Instead of "auto attach" (only for node.js, as I understand it) I would like to modify my launch.json so it extracts the process-id automatically, using e.g. the shell command: 'pgrep -x "$myprog"' and maybe optionally bind it to a keyboard-shortcut.

I'm guessing the line "processId": "${command:pickProcess}" needs to be modified, please see example configuration below:

{
    "name": "(gdb) Attach (any)",
    "type": "cppdbg",
    "request": "attach",
    "program": "/home/user/my-dev/bin/myApp",
    "processId": "${command:pickProcess}",
    "MIMode": "gdb",
    "miDebuggerPath": "/usr/bin/gdb"
},

Is it possible to modify the launch.json file so VS code understands that the variable "processId" should be substituted by the shell output from: pgrep -x "$myprog" (obviously this PID changes, after every compilation and execution of the program to be debugged)?

If so, I guess it is also possible to bind it to a keyboard-shortcut? Does anyone know how to achieve this?


Solution

  • Yes, it is possible with the use of the Tasks Shell Input Extension. It provides a vscode command that can return the result of a shell command.

    The relevant parts of my workspace looks like this.

    "launch": {
        "configurations": [
            {
                ...
                "processId": "${input:FindVivadoPID}",
                ...
            }
        ],
        "inputs": [
            {
              "id": "FindVivadoPID",
              "type": "command",
              "command": "shellCommand.execute",
              "args": {
                "command": "pgrep 'ecold.*lnx64.g/vivado' -f",
                "description": "Select your Vivado PID",
                "useFirstResult": true,
              }
            }
        ]
    }
    

    Whenever I run Start Debugging, it automatically finds the relevant process and attaches.

    See also using a shell command as VSCode task variable value which talks about the extension more generally.