c++linuxdebugginggdbassociate

Can I set a linux program to be started and attached by gdb?


On windows, I can set globalflag to associate the start of a program with a debugger, so even when I call a program from a script, the debugger will start my program and is able to break at some code line.

So how to do this with gdb on linux? E.g, I've /home/my/a.out compiled with -g option by gcc, I wish who ever calls into a.out, it will be brought up by gdb:

  1. Do I have to modify some system file to say, /home/my/a.out should be started by gdb and automatically attach?

  2. How to make gdb auto-attach it and then break at 'main' and run?


Solution

  • Do I have to modify some system file to say, /home/my/a.out should be started by gdb and automatically attach?

    You don't need to modify any system files to achive this. Modify /home/my/a.out instead.

    Move original binary to a new name:

    mv /home/my/a.out /home/my/a.out.orig
    

    Replace /home/my/a.out with a shell script:

    cat > /home/my/a.out <<'EOF'
    #!/bin/sh
    exec gdb -ex start --args /home/my/a.out.orig "$@"
    EOF
    chmmod +x /home/my/a.out
    

    How to make gdb auto-attach it and then break at 'main' and run?

    Above script will do that automatically.