fork()浅学习
原文链接:https://blog.csdn.net/qq_39355828/article/details/120153146 (opens new window)
# fork()浅学习
# 1.进程的创建 fork
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
int x=42;
int rc= fork();
if(rc<0)
fprintf(stderr,"failed");
else if(rc==0)
printf("Child process:rc: %d,value of x is:%d\n",rc,x);
else
printf("Parent process: rc: %d,value of x is:%d\n",rc,x);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fork():调度成功:则子进程的返回值为0,对于父进程则返回为进程的PID。但两个进程有着相同的状态,内存,寄存器,PC 等。,所以x是相等的。

#include<fcntl.h>
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
char str[11]={0};
int main()
{
int fd=open("test.txt",O_RDWR);
if(fork()==0)
{ssize_t cnt=read(fd,str,10);
printf("Child process: %s\n",str);
}
else
{
ssize_t cnt=read(fd,str,10);
printf("Parent process: %s\n",str);
}
close(fd);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
test.txt中的英文字母为26个英文字符,则输出的结果为:

当一个进程fork之后,整个进程表项被复制,包括所有的文件描述符。 但是文件表项并不会被复制。父进程和子进程共享相同的文件表项。
注意:文件的偏移量是储存在文件表项中,所以当一个进程读取了文件之后,另一个进程读取相同的文件会从上一个进程停止的地方开始读取。
#include <stdio.h>
#include <sched.h>
int data = 10;
int child_process()
{
printf("Child process %d, data %dn",getpid(),data);
data = 20;
printf("Child process %d, data %dn",getpid(),data);
while(1);
}
int main(int argc, char* argv[])
{
if(fork()==0) {
child_process();
}
else{
sleep(1);
printf("Parent process %d, data %dn",getpid(), data);
while(1);
}
}
运行结果
Child process 6427, data 10
Child process 6427, data 20
Parent process 6426, data 10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
第 1个Child process 6427, data 10是因为子进程创建时task_struct的mm直接拷贝自parent的mm;第2个Child process 6427, data 20是因为子进程进行了“写时拷贝”,有了自己的dataa;第3个Parent process 6426, data 10输出10是因为子进程的data和父进程的data不是同一份。
编辑 (opens new window)
上次更新: 2026/08/11, 13:36:18