Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

unix

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 exec command?

To clarify the problem:

I am running a program prog1. To enter a particular section in the program I have to give a SIGALRM 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 argv[0] 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 ;/bin/myprogram instead of argv[0]. Bottom line: I need /bin/myprogram to be executed with the privilege of prog1 and it's output.

like image 996
hax Avatar asked Jan 01 '26 19:01

hax


1 Answers

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
like image 132
rici Avatar answered Jan 03 '26 14:01

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!