简体   繁体   中英

Use of & in shell Scripting and Process Creation in Unix

The following is my code

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);
    }
}

Now i am writing a shell script to run it.The following is my shell script

#!/bin/sh

clear

gcc arg.c

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

The output is

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

However if i put & after Invocation$i in my script then the output is

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


Can you please explain the difference between the two outputs and the use of &.

And what should be done if i want each of the individual process created by fork method to end before starting the next

& causes the command before it to be run in the background. This means that the script continues immediately with the next statement, instead of waiting for the program to exit. In your case, this means that it goes immediately to the next iteration of the for loop, and runs ./a.out with the next invocation number.

When your program forks a child process, the order of running the child and parent is unpredictable. So sometimes it will print My child is before The Child is Invocation# , other times it will print them in the other order (and if the output weren't line-buffered, they might even get mixed together).

When you run the programs in the foreground, all the parent processes will run in the order that they were started, but the child processes can be mixed up. When you run all the programs in the background as well, all the parent and child processes run concurrently, and their ordering can be mixed up arbitrarily.

Your parent process doesn't call wait() , so it doesn't wait for the child to finish before it exits. So in the case where you run the program in the foreground, the child of the first invocation might not run until after parent exits and later invocations of the program are started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM