tags:

views:

184

answers:

3

In Perl, is it possible to determine if a script is being executed within another script (presumably via system or qx)?

$ cat foo.pl
print "foo";
print "\n" if not $in_qx;  # or the like.

I realize this is not applicable if the script was being run via exec.

I know for certain that system runs the process as a fork and I know fork can return a value that is variable depending on whether you are in the parent or the child process. Not certain about qx.

Regardless, I'm not certain how to figure out if I'm in a forked process without actually performing a fork.

+2  A: 

Do you control the caller? The simplest thing to do would be to pass an argument, e.g. --isforked.

Michael Carman
No, not really. My script is acting as a wrapper for another, I don't really have the ability to modify the arguments.
Danny
+5  A: 

You could check "who's your daddy", using "getppid" (get parent id). Then check if your parent id is a perl script with pgrep or similar.

wazoox
getppid (and most of the get* functions) aren't implemented on all platforms. Even where they are, you would have to determine if the PID belonged to an instance of perl, the shell, or something else.
Michael Carman
Well he's running on some standard linux so this is probably no issue there. Anyway it's some sort of kludge, there isn't any sure and clean approach here.
wazoox
+6  A: 

All processes are forked from another process (except init). You can sort of tell if the program was run from open, qx//, open2, or open3 by using the isatty function from POSIX, but there is no good way to determine if you are being run by system without looking at the process tree, and even then it can get murky (for instance system "nohup", "./foo.pl" will not have the calling perl process as its parent).

Chas. Owens