1 #include <unistd.h> //定义该函数 2 #include <sys/types.h> //定义函数的返回类型pid_t 3 /* 4 功能:复制进程 5 参数:无 6 返回值: 成功: 父进程:返回子进程id 7 子进程:返回0 8 失败: 返回-1 9 */ 10 pid_t fork(void); 11 12 函数说明: 13 一个现有进程可以调用fork函数创建一个新进程。由fork创建的新进程被称为子进程(child process)。fork函数被调用一次但返回两次。两次返回的唯一区别是子进程中返回0值而父进程中返回子进程ID。
数据共享:
子进程是父进程的副本,它将获得父进程数据空间、堆、栈等资源的副本。注意,子进程持有的是上述存储空间的“副本”,这意味着父子进程间不共享这些存储空间。
UNIX将复制父进程的地址空间内容给子进程,因此,子进程有了独立的地址空间。在不同的UNIX (Like)系统下,我们无法确定fork之后是子进程先运行还是父进程先运行,这依赖于系统的实现。所以在移植代码的时候我们不应该对此作出任何的假设。
或者说两进程共享代码空间,但是数据空间是互相独立的,子进程数据空间中的内容是父进程的完整拷贝,指令指针也完全相同,子进程拥有父进程当前运行到的位置(两进程的程序计数器pc值相同,也就是说,子进程是从fork返回处开始执行的)。
测试代码:
1 #include <unistd.h> 2 #include <sys/types.h> 3 #include <stdio.h> 4 int main(void) 5 { 6 pid_t pid; 7 pid=fork(); 8 switch (pid) 9 { 10 case -1: 11 perror("fork error"); 12 exit(1); 13 case 0: 14 printf("I am the child process, my process id is %d/n", getpid()); 15 break; 16 default: 17 printf("I am the parent process, my process id is %d/n", getpid()); 18 break; 19 } 20 return 0; 21 }
参考学习资料
请问下面的程序一共输出多少个“-”