Skip to content

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

$ sh
Hello world called from

# 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.



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 and shell script as

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)




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

('Parent process ID of current process is:', 15382)
('The parent process name is: ', '')
3 People found this is helpful