Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out what script, program, or shell executed my Perl script?

How would I determine what script, program, or shell executed my Perl script?

Example: I might want to have human readable output if executed from shell (customized for each type of shell), a different type of output if called as a script from another perl script, and a machine readable format if executed from a program such as a continuous integration server.

Motivation: I have a tool that changes its output based on which shell executes it. I'd normally implement this behavior as an option to the script, but this tool's design doesn't allow for options. Other shells have environment variables that indicate what shell is running. I'm working on a patch to support Powershell, which has no such special variable.

Edit: Many of these answers happen to be linux specific. Unfortuantely, Powershell is for Windows. getppid, the $ENV{SHELL} variable, and shelling out to ps won't help in this case. This script needs to run cross-platform.

like image 238
Robert P Avatar asked Dec 16 '11 19:12

Robert P


1 Answers

You use getppid(). Take this snippet in child.pl:

my $ppid = getppid();
system("ps --no-headers $ppid");

If you run it from the command line, system will show bash or similar (among other things). Execute it with system("perl child.pl"); in another script, e.g. parent.pl, and you will see that perl parent.pl executed it.

To capture just the name of the process with arguments (thanks to ikegami for the correct ps syntax):

my $ppid = getppid();
my $ps = `ps --no-headers -o cmd $ppid`;
chomp $ps;

EDIT: An alternative to this approach, might be to create soft links to your script, make the different contexts use different links to access your script and inspect $0 to build logic around that.

like image 194
flesk Avatar answered Oct 20 '22 21:10

flesk