Although the answers given are valid, sometimes you don't have permissions to change the script to execute gdb or to modify the program to add additional output to attach through pid.
Luckily, there is yet another way through the power of bash
Use ps, grep and awk to pick-out the pid for you after its been executed. You can do this by either wrapping the other script with your own or by just executing a command yourself.
That command might look something like this:
process.sh
#!/usr/bin/env bash
#setup for this example
#this will execute vim (with cmdline options) as a child to bash
#we will attempt to attach to this process
vim ~/.vimrc
To get gdb to attach, we'd just need to execute the following:
gdb --pid $(ps -ef | grep -ve grep | grep vim | awk '{print $2}')
- I use
ps -ef
here to list the processes and their arguments. Sometimes, you'll have multiple instances of a program running and need to further grep down to the one you want
- the
grep -ve grep
is there because the f
option to ps will include the next grep
in its list. If you don't need the command arguments for additional filtering, don't include the -f
option for ps and ignore this piece
grep vim
is where we're finding our desired process. If you needed more filtering, you could just do something like grep -E "vim.*vimrc"
and filter down to exactly the process that you're trying to attach to
awk '{print $2}'
simply outputs just the process' pid to stdout. Use $1
if you're using ps -e
instead of ps -ef
My normal setup is to run such script that starts my process in 1 tmux pane and having typed something similar to the above in a bottom pane. That way if I need to adjust the filtering (for whatever reason), I can do it pretty quickly.
Usually though, it will be the same for a specific instance and I want to just attach automatically after its been started. I'll do the following instead:
runGdb.py
#!/usr/bin/env bash
./process.sh &
PID=$(ps -ef | grep -ve grep | grep -E "vim.*vimrc" | awk '{print $2}')
#or
#PID=$(ps -e | grep vim | awk '{print $1}')
gdb --pid $PID
This assumes that the original process can be safely run in the background.
set follow-fork-mode child
would be all we need to do to get to the code we are interested in... – jww