pid_t fork(void);//创建子进程不阻塞父进程
pid_t vfork(void);//创建子进程并阻塞父进程
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/types.h>
5
6
7 int main(void)
8 {
9 pid_t pid;//pid 是一个无符号整型,打印时用%u,而不是%d
10
11 pid = fork();
12 if(pid < 0)
13 {
14 perror("fail to fork");
15 }
16 else if(pid == 0)
17 {
18 //子进程
19 printf("This is child\n");
20 printf("This is child PID : %u, parent :%u\n", getpid(), getppid());//获取子进程id,父进程id
21
22 exit(0);
23 }
24 else
25 {
26 //父进程
27
28
29 printf("This is parent\n");
30 printf("This is parent PID : %u\n", getpid());
31 exit(0);
32 }
33 }
vfork()函数和fork()函数的区别:
1.vfork()函数创建的子进程和父进程共享地址空间,包括数据段,代码段,堆栈段,子进程修改这些共享的资源会影响父进程.
2.vfork()函数创建的子进程一定比父进程先运行,因为父进程被阻塞,等待子进程运行完之后,再运行.