2015-08-19 33 views
0

以下是我的代码使用和在shell脚本和进程创建在Unix中

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 


能否请您解释一下这两个输出和使用&之间的差异。

如果我想通过每一个叉方法创建的各个过程,以开始下一个

+0

是否有关于您试图了解的输出的具体问题?你知道shell中的'&'是什么吗? –

+0

其实他们都是。但主要是为什么输出是不同的。 –

+0

您的文本编辑器是否损坏?你的代码示例看起来非常难看。 – hek2mgl

回答

4

&导致命令之前,它在后台运行结束之前,应该做些什么。这意味着脚本会立即继续执行下一条语句,而不是等待程序退出。在你的情况下,这意味着它会立即转到for循环的下一次迭代,并使用下一个调用编号运行./a.out

当您的程序分叉子进程时,运行子进程和父进程的顺序是不可预知的。所以有时它会在The Child is Invocation#之前打印My child is,有时它会以另一种顺序打印它们(如果输出不是行缓冲的,它们甚至可能混合在一起)。

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

您的父母程序不会呼叫wait(),因此它不会等到孩子退出前完成。因此,在前台运行程序的情况下,第一次调用的子程序可能无法运行,直到父程序退出并且稍后调用程序启动为止。

+0

但是,当我调用下一个调用之前,删除&.As中不应该首先调用完成后会发生什么? –

+0

是的。但是你的父进程不调用'wait()',所以它可以在子进程完成之前退出。 – Barmar