反引号命令中的独立 child

Standalone child in backtick command

这是执行 perl 脚本的主脚本 "fork.pl" #!/bin/bash

OUTPUT=`./fork.pl`
echo "$OUTPUT"

以及 fork.pl: #!/usr/bin/perl

use strict;
use warnings;
use POSIX;

my $pid = fork();

if ($pid == 0) {
    sleep(5);
    print("child: $pid\n");
}

else {
    print("parent: $pid\n")
}

反引号表示等待,但我不想等待最后一个child。 谢谢

不等待终止的方法之一是在后台启动,同时将输出重定向到文件。然后尝试阅读带有 shell 的 read.

的行

例如,读取第一行的 hack:

./fork.pl > temp.out &
sleep 1
read OUTPUT < temp.out

或者,没有 sleep,但限于 do/done 块:

./fork.pl | while read OUTPUT; do
     # use $OUTPUT here
     break   # first line only, or loop conditionally
done

它需要从父级分离并重定向 input/output :

if ($pid == 0) {
    my $mysid = setsid();
    open (STDIN, "</dev/null");
    open (STDOUT, ">/dev/null");
    open (STDERR, ">&STDOUT");

    sleep(5);
    print("child: $pid\n");
}