Danny
Danny

Reputation: 14144

How can I determine if the script is being executed within a system or qx call in Perl?

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.

Upvotes: 3

Views: 915

Answers (3)

Chas. Owens
Chas. Owens

Reputation: 64919

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

Upvotes: 6

wazoox
wazoox

Reputation: 1392

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.

Upvotes: 5

Michael Carman
Michael Carman

Reputation: 30831

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

Upvotes: 2

Related Questions