#include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() { pid_t self, parent, child; self = getpid(); parent = getppid(); int i=0, n=0; printf("PID: %d, PPID: %d (before fork) \n", self, parent); child =fork(); if(child==0) { // child process printf("child=fork() == 0 (child process)\n"); printf("PID: %d, PPID= %d\n", getpid(), getppid()); // i, n in child process // to demostrate child and process have their own data. for(i=0; i<5; i++) { printf("[Child ] i=%d, n=%3d\n", i, n+=10); sleep(1); } } else { // parent process printf("child=fork() != 0 (parent process)\n"); printf("PID: %d, PPID= %d\n", getpid(), getppid()); // i, n in parent process // to demostrate child and process have their own data. for(i=0; i<5; i++) { printf("[Parent] i=%d, n=%3d\n", i, n+=100); sleep(1); } } return 0; }Thanks to Online syntax highlighting http://tohtml.com/ .
2009/05/11
fork() demo
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言