【问题标题】:start new shell from perl script and execute the rest of code on the child shell从 perl 脚本启动新的 shell 并在子 shell 上执行其余代码
【发布时间】:2015-03-17 19:22:10
【问题描述】:

我想从 perl 启动一个新的 shell(我正在通过 exec 语句执行此操作)。当子 shell 启动时,我想在新 shell 上打印一些消息并想在子 shell 上运行另一个 perl 脚本。

我正在这样做:

exec $ENV{SHELL};

请帮忙。

【问题讨论】:

  • 展示你是如何使用“exec 语句”的。例如显示您尝试过的内容。 ;)(你可以编辑你的问题)
  • 不会有带有execchild shell(子shell 只能由fork() 创建)。您的 perl 脚本被您执行的任何程序替换。正确的术语是被执行的shell。您能否重新表述您的问题,以便我们更好地理解它?
  • 请在执行 perl 脚本之前和之后检查 ps 命令的输出,其中包含简单的 exec $ENV{SHELL}。它实际上会创建一个子shell

标签: perl


【解决方案1】:

取决于你想做什么。

我认为你追求的是反勾号``

查看http://perldoc.perl.org/perlop.html#%60STRING%60,它有一些关于如何捕获外部命令输出的好例子。请注意,反引号会分叉。

我喜欢使用 Perls 引用,例如运算符 qx 来代替反引号。

http://perldoc.perl.org/perlop.html#Quote-Like-Operators

示例:

my $ls = qx/ls/;
my $ret_ls = $? >> 8;

print "Output: $ls\nExit Code: $ret_ls";

其他脚本示例:

my $other_script_output = qx{/path/to/other_script.pl};
my $ret_other_script = $? >> 8;

print "Output: $other_script_output\nExit Code: $ret_other_script";

如果您正在寻找以编程方式与该进程交互,那么您将深入研究 open2 / open3。

【讨论】:

    【解决方案2】:

    我认为你正在寻找的是

    use strict;
    use warnings;
    
    open my $fh, '|-', $ENV{SHELL};
    print $fh <<'EOF';
    echo "$0: From shell goes hell"
    EOF
    

    注意''EOF' 附近,它禁用了shell 脚本的Perl 插值,但$0 是由shell 插值的。您必须转义 \$0 否则才能获得 shell 可执行文件。详情请见perlop Here-document

    您也可以为此目的使用现有的文件句柄

    use strict;
    use warnings;
    
    close STDIN;
    open STDIN, '<&', \*DATA;
    exec $ENV{SHELL};
    __DATA__
    echo "$0: From shell goes hell"
    

    注意open my $fh, '|-', $ENV{SHELL}; 只是open my $fh, '|-' or exec $ENV{SHELL}; 的语法糖,其中open my $fh, '|-' 是某些pipeclosedupfork 杂耍的语法糖。

    但是这段代码不起作用

    use strict;
    use warnings;
    
    my $script = <<'EOF';
    echo "$0: From shell goes hell"
    EOF
    
    close STDIN;
    open STDIN, '<', \$script; # this is not real file handler!
    exec $ENV{SHELL};
    

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多