簡體   English   中英

在Unix中使用&in shell腳本和過程創建

[英]Use of & in shell Scripting and Process Creation in 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


您能否解釋一下兩個輸出之間的區別以及&的用法。

如果我希望由fork方法創建的每個單獨進程在開始下一個之前結束,該怎么辦

&導致該命令在后台運行。 這意味着腳本將立即繼續執行下一條語句,而不是等待程序退出。 在您的情況下,這意味着它將立即進入for循環的下一個迭代,並使用下一個調用號運行./a.out

當程序派生子進程時,運行子進程和父進程的順序是不可預測的。 因此,有時它會在The Child is Invocation#之前打印“ My child is The Child is Invocation# ,而有時它會以其他順序打印(如果輸出不是行緩沖的,則它們甚至可能混合在一起)。

當您在前台運行程序時,所有父進程將按照啟動順序運行,但是子進程可以混合在一起。 當您同時在后台運行所有程序時,所有父進程和子進程同時運行,並且其順序可以任意混合。

您的父進程不會調用wait() ,因此它不會在子級退出之前等待子級完成。 因此,在前台運行程序的情況下,第一次調用的子級可能要等到父級退出並隨后啟動程序的調用之后才能運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM