简体   繁体   中英

How to know the called program path in C/C++ in Linux?

I am having a compiled C program say test in /usr/bin and a python program say pgm.py is in /opt/python/ . In pgm.py , I am calling the C program like os.system("test arg1 arg2") . Is it possible for the C program to know that it is being called by /opt/python/pgm.py ?

Misc operating system interfaces will have the information you want. One way would be to get the python program to write the information to a temp file, and then pass the file as a c-line arg into the C program.

Assuming you're using something akin to Linux, you could use a platform-specific solution. For simplicity, I'm using a Python script test.py in place of a binary.

pgm.py

#!/usr/bin/env python
import os

os.system('python test.py')

test.py

#!/usr/bin/env python
import os, errno

pid = os.getpid()

while 1:
    try:
        pid = int(open('/proc/%d/stat' % pid).read().split()[3])
        cmd = os.readlink('/proc/%d/exe' % pid)
        args = open('/proc/%d/cmdline' % pid).read().split('\0')
    except OSError as e:
        if e.errno == errno.EACCES:
            print 'Permission denied for PID=%d' % pid
            break
        raise
    print pid, cmd, args
    if pid == 1:
        break

When running pgm.py , I get the output...

341 /bin/dash ['sh', '-c', 'python test.py', '']
340 /usr/bin/python2.7 ['python', './pgm.py', '']
13888 /bin/bash ['-bash', '']
Permission denied for PID=13887

So you could test use a simple comparison in test which does something similar.

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