如何确定脚本是在系统内执行还是在Perl中调用qx?

时间:2021-04-22 07:16:08

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

在Perl中,是否可以确定脚本是否正在另一个脚本中执行(可能是通过系统或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.

我意识到如果脚本是通过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.

我确定系统将进程作为fork运行,我知道fork可以返回一个可变的值,具体取决于您是在父进程还是子进程中。关于qx不确定。

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

无论如何,我不确定如何在没有实际执行fork的情况下弄清楚我是否处于分叉进程中。

3 个解决方案

#1


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

所有进程都是从另一个进程(init除外)分叉的。您可以通过使用POSIX中的isatty函数来判断程序是从open,qx //,open2还是open3运行,但没有好的方法可以确定您是否在没有查看进程树的情况下由系统运行,即使这样它也会变得模糊(例如系统“nohup”,“。/ foo.pl”将不会将调用perl进程作为其父进程)。

#2


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.

您可以使用“getppid”(获取父ID)来检查“谁是您的爸爸”。然后检查您的父ID是否是带有pgrep或类似的perl脚本。

#3


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

你控制了来电者吗?最简单的方法是传递一个参数,例如: --isforked。

#1


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

所有进程都是从另一个进程(init除外)分叉的。您可以通过使用POSIX中的isatty函数来判断程序是从open,qx //,open2还是open3运行,但没有好的方法可以确定您是否在没有查看进程树的情况下由系统运行,即使这样它也会变得模糊(例如系统“nohup”,“。/ foo.pl”将不会将调用perl进程作为其父进程)。

#2


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.

您可以使用“getppid”(获取父ID)来检查“谁是您的爸爸”。然后检查您的父ID是否是带有pgrep或类似的perl脚本。

#3


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

你控制了来电者吗?最简单的方法是传递一个参数,例如: --isforked。