Home > Software design >  Program to find from where the program is called
Program to find from where the program is called

Time:02-10

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.

CodePudding user response:

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')

CodePudding user response:

You can get the caller and the command with all its arguments as a string by passing the $PPID variable to ps, example:

printf "Called from: %s\n" "$(ps -o args= $PPID)"

Sample output:

Called from: /bin/bash ./caller.sh

For more output options see the ps man page

  • Related