c - combine fork execl wait -
i have create prog1 take 1 argument number of children have create. (example "./prog1 5" - create 5 children) each of children generate random number 1 20. number given execl start prog2 (in same folder) take argument random number. prog2 should sleep random number time. after should return random number parent.
created still don't work properly.
prog1:
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> int main(int argc, char *argv[]) { int n, i, pid; int u = getppid(); int procesy = 0; pid_t proc_id; n = atoi(argv[1]); for(i = 0; < n; i++) { proc_id = fork(); if(proc_id==0) { srand(getpid()); u = 1 + rand()%20; execl("./prog2", "prog2", u,0); } else { procesy++; } } if(u == getppid()) { for(i = 0; < n; i++) { pid = wait(&u); printf("process %d ende\n", pid); procesy--; } if(procesy == 0) printf("endc\n"); } return 1; }
prog2:
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> int main(int argc, char *argv[]) { int n; n = atoi(argv[1]); sleep(n); exit(n); }
change loop following, in order call execl():
if(proc_id==0) { char arg[16]; srand(getpid()); sprintf(arg, "%d", 1 + rand()%20); execl("./prog2", "prog2", arg, 0); printf("i should not here!\n"); exit(-1); }
then rid of if(u == getppid())
(but keep contents of conditional). seems if
trying filter out child running block. when execl()
works, child not going run anything in code after execl()
... printf , exit added not run. lines run if execl()
fails, , in simple case, way fail if you've provided improper arguments.
Comments
Post a Comment