使用&在Unix中的脚本脚本和进程创建

时间:2015-08-19 18:40:25

标签: linux shell unix process

以下是我的代码

main(int argc, char **argv){

    char *MyName=argv[1];
    int cpid=fork();

    if(cpid==0){
        printf("The Child is %s of %d\n",MyName,getpid());
        exit(0);
    }
    else{
        printf("My child is %d\n",cpid);
        exit(0);
    }
}

现在我正在编写一个shell脚本来运行它。以下是我的shell脚本

#!/bin/sh

clear

gcc arg.c

for((i=1;i<=5;i++))
do
    ./a.out Invocation$i 
done

输出

My child is 28629
My child is 28631
The Child is Invocation1 of 28629
My child is 28633
The Child is Invocation2 of 28631
My child is 28635
The Child is Invocation3 of 28633
My child is 28637
The Child is Invocation4 of 28635
The Child is Invocation5 of 28637

但是,如果我在&后面放Invocation$i,那么输出就是

My child is 29158
My child is 29159
My child is 29160
My child is 29161
The Child is Invocation4 of 29159
The Child is Invocation5 of 29158
The Child is Invocation3 of 29160
The Child is Invocation2 of 29161
My child is 29163
The Child is Invocation1 of 29163


你能否解释两个输出和&amp;的使用之间的区别。

如果我希望fork方法创建的每个进程在开始下一个

之前结束,应该怎么做

1 个答案:

答案 0 :(得分:4)

public override async void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { ... if (hub != null) { // THIS LINE THROWS THE ERROR var response = await actionExecutedContext.Response.Content.ReadAsAsync(actionExecutedContext.ActionContext.ActionDescriptor.ReturnType); hub.Clients.All.Invoke(OutgoingMethod, new { Time = DateTime.Now.ToString("G"), Data = response }); } } 导致之前的命令在后台运行。这意味着脚本会立即继续执行下一个语句,而不是等待程序退出。在您的情况下,这意味着它会立即进入&循环的下一次迭代,并使用下一个调用号运行for

当您的程序分叉子进程时,运行子进程和父进程的顺序是不可预测的。因此,有时它会在./a.out之前打印My child is,有时它会以其他顺序打印它们(如果输出没有行缓冲,它们甚至可能混合在一起)。

当您在前台运行程序时,所有父进程将按它们启动的顺序运行,但子进程可能会混淆。当您在后台运行所有程序时,所有父进程和子进程同时运行,并且它们的排序可以任意混合。

您的父进程未调用The Child is Invocation#,因此在退出之前,它不会等待孩子完成。因此,如果您在前台运行该程序,则第一次调用的子项可能不会运行,直到父项退出并且稍后启动该程序的调用。

相关问题