Skip to content
Advertisement

Program to find from where the program is called

The requirement is very simple, I want to write a simple hello world program or anything so the program knows about its execution parent. For eg.

Since I am from a Java background I will give a Java example. I want to write a jar that runs and outputs the following:

Running from command line:

$ java -jar myjar.jar
Hello world called from bash

but when running from myscript.sh:

$ sh myscript.sh
Hello world called from myscript.sh

myscript.sh

#!/bin/bash
#
# runs the jar
java -jar myjar.jar

Now, I am language agnostic regarding this so any language/library that can help me achieve this is welcome, the only requirement is it should be able to be called from a bash script and should recognize the script that calls it.

Every idea is welcomed.

Advertisement

Answer

You can achieve it in python like this:

Basically it should be same, be it any programming language. You need to get the parent process ID and name of the process associated with it. If you use Java program, I guess you can achieve the same there also.

I named the python script as test.py and shell script as test.sh

test.py

import os
import psutil

ppid = os.getppid()
process_name = psutil.Process(ppid).name()

print("Parent process ID of current process is:", ppid)
print("The parent process name is: ", process_name)

test.sh

#!/bin/bash

python test.py

Output:

python test.py
('Parent process ID of current process is:', 14866)
('The parent process name is: ', 'bash')


./test.sh
('Parent process ID of current process is:', 15382)
('The parent process name is: ', 'test.sh')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement