fork + exec +调用方不应等待子进程 [英] fork + exec + caller should not wait for child

查看:128
本文介绍了fork + exec +调用方不应等待子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个脚本script_a和script_b. script_a调用script_b. script_b分叉两个进程.如下所示.

I have two scripts script_a and script_b. script_a calls script_b. script_b forks two processes. As shown below.

script_a等待script_b的父级和子级都完成. 我希望script_a可以继续执行而不必等待script_b的子进程.

script_a waits for both the parent and child of script_b to finish. I want script_a to continue without waiting for the child process of script_b.

我为此做的是在script_b中,我添加了以下代码.

What I have done for this is in script_b, I have added the following code.

if (! $f_id) {
    close STDOUT;
    close STDERR;
    exec("sleep 10; echo 'i am child'");
}

这对我有用. script_a不再等待子进程.

This works for me. script_a no longer waits for the child process.

我的问题是 1.这是正确的方法吗? 2.父进程和子进程共享相同的STDOUT和STDERR,如果出现竞争情况,我是否会陷入麻烦? 3.有更好的方法吗?

My question here is, 1. Is this the right way to do this? 2. Do parent and the child process share the same STDOUT and STDERR and would I end up in trouble if there is a race condition? 3. Are there better ways to do this?

预先感谢您的帮助.

script_a.pl

script_a.pl

#! /usr/local/bin/perl
print `script_b.pl`;

script_b.pl

script_b.pl

#! /usr/local/bin/perl

$f_id = fork();

if (! $f_id) {
    exec("sleep 10; echo 'i am child'");
}

if ($f_id) {
    print "i am parent\n";
}

推荐答案

而不是在script_a中使用``.我们已经在script_a中重定向了STDOUT和STDERR. 像

Instead of using `` in script_a. We have redirected the STDOUT and STDERR in script_a. Something like

script_a

system("script_b.pl > /var/tmp/out_file 2>&1");

script_b

#! /usr/local/bin/perl

$f_id = fork();

if (! $f_id) {
    exec("sleep 10; echo 'i am child'");
}

if ($f_id) {
    print "i am parent\n";
}

通过这种方式,调用方不必等待exec中的孩子完成.

This way the caller didnot wait for the child in exec to complete.

感谢您的帮助.

这篇关于fork + exec +调用方不应等待子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆