#include "sys/types.h"#include "stdio.h"#include "stdlib.h"#include "unistd.h"int main(){pid_t pid;/*需要引入sys/types.h 和 unistd.h两个头文件创建进程 返回子进程的id 创建失败,返回-1;并提示错误信息,EAGAIN:表示fork()函数没有足够的内存用于复制父进程的分页表和进程结构数据ENOMEM:表示fork()函数分配必要的内核数据结构时,内存不足fork()函数会复制进程的所有资源,包括进程环境、内存资源,不与父进程共享*/int var=1;//测试是否共享堆栈段pid = fork();if (pid<0){printf("fork error!\n");}else if (pid==0){var=var+1;printf("in the child process! pid:%d,var:%d\n",pid,var);}else{var=var+3;printf("in the parent process pid:%d,var:%d\n",pid,var);}exit(0); }
打印结果:
in the child process! pid:0,var:2in the parent process pid:4316,var:4[Finished in 0.5s]
由此看出 fork()没有共享内存资源,仅仅是复制了父进程的所有资源