gpt4 book ai didi

perl - 从 perl 确定父 shell

转载 作者:行者123 更新时间:2023-12-02 01:48:56 25 4
gpt4 key购买 nike

从 perl 我想知道启动这个 perl 进程的 shell 的名称(可能还有路径)。

$ENV{SHELL} 不提供这个(它提供您的登录 shell - 但当前的 perl 进程可能从不同的 shell 启动)。

目前我找到的最佳答案是:http://www.perlmonks.org/?node_id=556926但这对不同平台的处理非常糟糕('ps' 的输出因平台而异)。

我试着查看 %ENV,但它只包含导出的变量。

那么有没有更好的办法呢?

背景

这将用于 GNU Parallel:每个作业都通过 shell 启动。为了尽量不给用户带来意外,这个 shell 应该是启动 GNU Parallel 的同一个 shell。这样,tcsh 用户将能够使用 GNU Parallel 运行他的 tcsh 命令,对于 bash/zsh/*sh 用户也是如此。

当前使用的是 $SHELL,但这会提供登录 shell 而不是当前的 shell,这让用户感到惊讶,因为他们运行的 shell 与登录 shell 不同。如果在由 tcsh 用户编写但由 bash 用户运行的脚本中使用 GNU Parallel,也会导致问题。

如果 GNU Parallel 不是从 shell 启动的,它将默认为 $SHELL(与现在相同)。

最佳答案

这样的事情怎么样:

#!/usr/bin/env perl

use strict;
use warnings;
use feature 'say';

use Proc::ProcessTable;

my $t = Proc::ProcessTable->new;

my $current_pid = $$;
my @parents;

# loop over the process table until we've found all the parents from perl pid
# up to init (process ID 1)
while ($current_pid != 1) {
for my $process (@{ $t->table }) {
if ($process->pid == $current_pid) {
push @parents, $process;
$current_pid = $process->ppid;
}
}
}

# loop over the parents we've found and look for something that looks like a
# shell command
for my $process (@parents) {
my $cmd = $process->cmndline;

if ($cmd =~ m/sh$/) {
say $cmd;
last;
}
}

关于perl - 从 perl 确定父 shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23937389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com