linux - Use of & in shell Scripting and Process Creation in Unix -


the following code

main(int argc, char **argv){      char *myname=argv[1];     int cpid=fork();      if(cpid==0){         printf("the child %s of %d\n",myname,getpid());         exit(0);     }     else{         printf("my child %d\n",cpid);         exit(0);     } } 

now writing shell script run it.the following shell script

#!/bin/sh  clear  gcc arg.c  for((i=1;i<=5;i++))     ./a.out invocation$i  done 

the output is

my child 28629 child 28631 child invocation1 of 28629 child 28633 child invocation2 of 28631 child 28635 child invocation3 of 28633 child 28637 child invocation4 of 28635 child invocation5 of 28637 

however if put & after invocation$i in script output is

my child 29158 child 29159 child 29160 child 29161 child invocation4 of 29159 child invocation5 of 29158 child invocation3 of 29160 child invocation2 of 29161 child 29163 child invocation1 of 29163 


can please explain difference between 2 outputs , use of &.

, should done if want each of individual process created fork method end before starting next

& causes command before run in background. means script continues next statement, instead of waiting program exit. in case, means goes next iteration of for loop, , runs ./a.out next invocation number.

when program forks child process, order of running child , parent unpredictable. print my child is before the child invocation#, other times print them in other order (and if output weren't line-buffered, might mixed together).

when run programs in foreground, parent processes run in order started, child processes can mixed up. when run programs in background well, parent , child processes run concurrently, , ordering can mixed arbitrarily.

your parent process doesn't call wait(), doesn't wait child finish before exits. in case run program in foreground, child of first invocation might not run until after parent exits , later invocations of program started.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

mysql - FireDac error 314 - but DLLs are in program directory -