#include /* printf, etc */ #include /* almost always need this with system programming */ #include /* fork, getpid, getppid */ /* Another fork test program - this one includes a command line option that specifies which process should call sleep if "-c" is specified the child sleeps, otherwise the parent sleeps */ int main(int argc, char **argv) { pid_t childpid; if (argc!=2) { printf("usage: %s (-p|-c)\n",argv[0]); exit(0); } if (childpid = fork()) { /* fork returns child's pid in the parent - this is parent only code */ if (strcmp(argv[1],"-c")!=0) { /* parent sleeps */ sleep(1); } printf("I am the parent, my pid is %u\n",getpid()); printf("My child's pid is (or was) %u\n",childpid); } else { /* fork returned 0 - this is child only code */ if (strcmp(argv[1],"-c")==0) { /* child sleeps */ sleep(1); } printf("I am the child, my pid is %u\n",getpid()); printf("My current parent's pid is %u\n",getppid()); } return(0); }