Any way for a perl script to know who called it and/or how?
Be it another script, or an executable. Straight from the command-line or the cron scheduler.
Tools to help track down how a Perl script was started:
getppid
returns parent process id. You can then use ps
or /proc/<pid>
to get more information about the calling process.
$^X
: full path to the perl interpreter, which may provide a clue about how Perl was started from the shell
$0
, __FILE__
: name of the script invoked from the command line, and the current file name. If they are consistent, then the current file contains the script that was invoked from the command line.
@ARGV
: command line arguments passed to your script. With $^X
, $0
, and @ARGV
, you know exactly how the Perl interpreter was started from the shell.
caller
: stack trace information. If caller
returns undef
at the start of a script, then you are at the top frame of the stack, and your script was invoked from the shell. Otherwise caller
returns the package, file, and line where your script was invoked (with do
or require
).
$^T
: time (in seconds since the "epoch") that the current Perl script was started, so you know when the current Perl interpreter was started from the shell. Use scalar localtime($^T)
to see this value in a friendlier format.
Aviatrix deleted an answer where he said, "Try using command-line arguments". This is a good idea. Programs that depend on things that can't be controlled are difficult to test. As you develop your script, do you really want to run it from cron to test the "being run from cron" functionality? No way!
So instead of making your script guess what it's being run from, just tell it. Then it won't have to guess, and then it won't guess incorrectly (at three in the morning, no doubt).
Reliable software is a pure function from its input to its output. Don't add impurity without an excellent reason. ("I want it to randomly be different when run from cron" is not a good reason.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With