#include <sys/types.h> #include <stdio.h> #include <unistd.h> #include <sys/wait.h> using namespace std; int main () { int pid; printf ("\ni'm original process pid %d.\n", getpid ()); pid = fork (); /* duplicate process. child , parent continue here */ if (pid != 0) /* pid non-zero, must parent */ { printf ("i'm parent process pid %d.\n", getpid()); printf ("my child's pid %d.\n", pid); } else /* pid zero, must child */ { printf ("i'm child process pid %d.\n", getpid ()); pid= fork(); printf ("i'm child's child pid %d.\n", getpid ()); } printf ("pid %d terminates.\n", getpid()); }
so far program working, need program continue 9 more processes indicating process 2 parent of process 3 , process 3 parent of process 4, , on. far i've been able output parent process id, along child process id. issue is, outputs parent , child once. require program create chain of 10 processes , prints out parent , child process id's. i've been able output parent id , child id once. best method accomplish this?
you can try out this:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> static int counter = 1; void init_proc() { pid_t pid; pid = fork(); if(pid==0) { if(counter==10) { return; } else { counter++; init_proc(); } } else if(pid > 0) { int status; waitpid(pid, &status, wnohang); printf("process %d child %d\n", getpid(), pid); } else { fprintf(stderr,"error: not initialize process\n"); } } int main () { init_proc(); return 0; }
notice pid != 0
doesn't mean in parrent process. if fork()
returns -1 means there error. more info here: http://linux.die.net/man/2/fork .
in example didn't use printf's wanted can play little results want.
Comments
Post a Comment