How do I run a program with commandline args using

2019-01-20 21:17发布

When running a program on gdb, usually, the arguments for the program are given at run command. Is there a way to run the program using gdb and as well as give arguments within a shell script?

I saw an answer in a related question, mentioning that we can attach the gdb to the program after script starts executing. But then I will have to 'wait' the program.

I'm curious whether there is any other way to do this.

8条回答
Animai°情兽
2楼-- · 2019-01-20 21:25

If the --args parameter is not working on your machine (i.e. on Solaris 8), you may start gdb like

gdb -ex "set args <arg 1> <arg 2> ... <arg n>"

And you can combine this with inputting a file to stdin and "running immediatelly":

gdb -ex "set args <arg 1> <arg 2> ... <arg n> < <input file>" -ex "r"
查看更多
叛逆
3楼-- · 2019-01-20 21:27

gdb has --init-command <somefile> where somefile has a list of gdb commands to run, I use this to have //GDB comments in my code, then `

echo "file ./a.out" > run
grep -nrIH "//GDB"|
    sed "s/\(^[^:]\+:[^:]\+\):.*$/\1/g" |
    awk '{print "b" " " $1}'|
    grep -v $(echo $0|sed "s/.*\///g") >> run
gdb --init-command ./run -ex=r

as a script, which puts the command to load the debug symbols, and then generates a list of break commands to put a break point for each //GDB comment, and starts it running

查看更多
Luminary・发光体
4楼-- · 2019-01-20 21:30

You can run gdb with --args parameter,

gdb --args executablename arg1 arg2 arg3

If you want it to run automatically, place some commands in a file (e.g. 'run') and give it as argument: -x /tmp/cmds. Optionally you can run with -batch mode.

gdb -batch -x /tmp/cmds --args executablename arg1 arg2 arg3
查看更多
forever°为你锁心
5楼-- · 2019-01-20 21:30
gdb -ex=r --args myprogram arg1 arg2

-ex=r is short for -ex=run and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.

查看更多
冷血范
6楼-- · 2019-01-20 21:32

You could create a file with context:

run arg1 arg2 arg3 etc

program input

And call gdb like

gdb prog < file
查看更多
叛逆
7楼-- · 2019-01-20 21:38

Another way to do this, which I personally find slightly more convenient and intuitive (without having to remember the --args parameter), is to compile normally, and use r arg1 arg2 arg3 directly from within gdb, like so:

$ gcc -g *.c *.h
$ gdb ./a.out
(gdb) r arg1 arg2 arg3
查看更多
登录 后发表回答