#include
#include
int main(int argc,char *argv[]){ //fork函数使用 int i = 0; printf("before fork\n"); pid_t pid = fork(); printf("after fork\n"); if (pid < 0){ printf("error\n"); return 1; } else if (pid == 0){ printf("fork success,this is son process\n"); while (i<10){ i += 1; printf("this is son process,i=%d\n",i); sleep(1); } } else{ printf("fork success,this is father process,son process id is %d \n",pid); while (i<10){ i += 2; printf("this is father process,i=%d\n",i); sleep(2); } } return 0; }
运行结果:
before fork after fork fork success,this is father process,son process id is 11054 this is father process,i=2 after fork fork success,this is son process this is son process,i=1 this is son process,i=2 this is father process,i=4 this is son process,i=3 this is son process,i=4 this is father process,i=6 this is son process,i=5 this is son process,i=6 this is father process,i=8 this is son process,i=7 this is son process,i=8 this is father process,i=10 this is son process,i=9 this is son process,i=10
在程序中,我们可以看到,fork函数调用之后,输出了两个“after fork”,也就是程序已经存在两个进程在跑;有一个变量i,在fork之前定义,然后在fork之后的运行过程中,子进程和主进程中的i值互不影响,两个进程同时在执行,可以验证fork是将主进程的资源全部拷贝了一份给子进程,两个进程的资源是独立的,互不影响。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/215819.html原文链接:https://javaforall.net
