parent process create child process
add value util bigger than five and then exit
#include <unistd.h> /* Symbolic Constants */ #include <sys/types.h> /* Primitive System Data Types */ #include <errno.h> /* Errors */ #include <stdio.h> /* Input/Output */ #include <sys/wait.h> /* Wait for Process Termination */ #include <stdlib.h> /* General Utilities */ int main() { pid_t childpid; /* variable to store the child's pid */ int value=0; /* parent process: child's exit status */ /* only 1 int variable is needed because each process would have its * own instance of the variable * here, 2 int variables are used for clarity */ /* now create new process */ childpid = fork(); if (childpid >= 0) /* fork succeeded */ { if (childpid == 0) /* fork() returns 0 to the child process */ { printf("Child: Here's my PID: %d\n", getpid()); while(value<5){ value+=1; printf("Child value= %d\n",value); sleep(1); } printf("Child: Goodbye!\n"); exit(0); } else /* fork() returns new pid to the parent process */ { printf("Parenet: Here's my PID: %d\n", getpid()); while(value<5){ value+=1; printf("Parent value= %d\n",value); sleep(1); } printf("PARENT: Goodbye!\n"); exit(0); /* parent exits */ } } else /* fork returns -1 on failure */ { perror("fork"); /* display error message */ exit(0); } |
makefile
fork:fork.o cc -o fork fork.o fork.o:fork.c cc -c fork.c clean: rm -rf fork *.o |
全站熱搜