hax hax - 1 year ago 54
Bash Question

How can I pass a custom string as argv[0] to a program

I have a C program which uses argv[0] inside the program. I understand that argv[0] is the path of the program being executed. I want to pass a custom string as argv[0] to the program instead of its program name. Is there a way to do this in shell?

I read about exec command. But I am unsure about the usage.

help exec
says I have to pass
exec -a <string>

  1. Is there any other way of doing this?

  2. Is there any escape method which I need to use if I am passing special characters or path of another file using

To clarify the problem:

I am running a program
. To enter a particular section in the program I have to give a
to the program. This step itself was difficult as I had to create a race around condition to send the signal right when the program starts.

while true;do ./prog1 2; done & while true; do killall -14 prog1; done

The above while loops help me to enter the part of program and that part of program uses
for a system call. This system call is
system(echo something argv[0])

Is there a way to modify the above while loop and put
instead of
Bottom line:
I need /bin/myprogram
to be executed with the privilege of
and it's output.

Answer Source

exec -a is precisely the way to solve this problem.

There are no restrictions that I know of on the string passed as an argument to exec. Normal shell quoting should be sufficient to pass anything you want (as long as it doesn't contain embedded NUL bytes, of course).

The problem with exec is that it replaces the current shell with the named command. If you just want to run a command, you need to spawn a new shell to be replaced; that is as simple as surrounding the command with parentheses:

$ ( exec -a '; /bin/myprogram' bash -c 'echo "$0"'; )
; /bin/myprogram
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download