简体   繁体   中英

Need to get C program name inside shell script

I have an occasion where a C program invokes a shell script, which in-turn does some copying stuff from the CD mount location to an installation directory.

Now my question is that, is there a straightforward approach to get the absolute path of this C program inside this shell script ?.

I tried a couple of approaches that includes using "$(ps -o comm= $PPID)" from within the script, but nothing did work out till now. I know that I can create a temporary file from the C program which contains its own name (argv[0]) and then make the shell script to read that file, but I don't want to follow that approach here.

Of course, it can be passed as an argument to the script, but I was thinking why the bash built-in macros or something cannot be used here

On linux there is a /proc/self/exe path that points the absolute path of the current executed file. So you can push an environment variable that contains the path before spawning the shell. Something like:

readlink("/proc/self/exe",...,buf);
putenv("MYEXE",buf);
system("thescript");

and accessing the variable in the script:

echo $MYEXE

Before running a foo command you could use which like

fooprog=$(which foo)

to get the full path of the program (scanning your $PATH ). For example which ls could give /bin/ls ....

On Linux specifically you could use proc(5) .

In your shell process (running bash or some POSIX compliant shell) started by your C program, $PPID give the parent process id, hopefully the pid of the process running your C program.

Then the executable is /proc/$PPID/exe which is a symbolic link. Try for example the
ls -l /proc/$PPID/exe command in some terminal.

(notice that you don't run C source files or stricto sensu C programs, you often run some ELF executable which was built by compiling C code)

You might have weird cases (you'll often ignore them, but you might decide to handle them). Someone might move or replace or remove your executable while it is running. Or the parent process (your executable) died prematurely, so the shell process becomes orphan . Or the executable removed itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM