FORK()子进程对父进程打开的文件描述符的处理

总的来说,子进程将复制父亲进程的数据段,BSS段,代码段,堆空间,栈空间和文件描述符。而对于文件技术符关联内核文件表项(即STRUCT FILE结构),则是采取了共享的方式。

下面代码说明。

I值分离,但FD共享。

 1 [root@localhost ~]# vim fork_descriptor.c
 2 #include <stdio.h>
 3 #include <sys/types.h>
 4 #include <unistd.h>
 5 #include <fcntl.h>
 6 #include <string.h>
 7 #include <stdlib.h>
 8 
 9 int main(int argc, char *argv[])
10 {
11     pid_t pid;
12     int fd;
13     int i = 1;
14     int status;
15     char *ch1 = "hello";
16     char *ch2 = "world";
17     char *ch3 = "IN";
18     if((fd = open("test.txt", O_RDWR | O_CREAT, 0644)) == -1)
19     {
20         perror("parent open");
21         exit(EXIT_FAILURE);
22     }
23     if(write(fd, ch1, strlen(ch1)) == -1)
24     {
25         perror("parent write");
26         exit(EXIT_FAILURE);
27     }
28     if((pid = fork()) == -1)
29     {
30         perror("fork");
31         exit(EXIT_FAILURE);
32     }
33     else if(pid == 0)
34     {
35         i = 2;
36         printf("in child\n");
37         printf("i = %d\n", i);
38         if(write(fd, ch2, strlen(ch2)) == -1)
39             perror("child write");
40         return 0;
41     }
42     else
43     {
44         sleep(1);
45         printf("in parent\n");
46         printf("i = %d\n", i);
47         if(write(fd, ch3, strlen(ch3)) == -1)
48             perror("parent write");
49         wait(&status);
50         printf("\n");
51         return 0;
52     }
53 }
54 "fork_descriptor.c" 53L, 945C written  

结果:

[root@localhost ~]# gcc -o fork_descriptor fork_descriptor.c

[root@localhost ~]# ./fork_descriptor

in child i = 2

in parent i = 1

[root@localhost ~]# cat test.txt

helloworldIN

上一篇:你知道吗?macOS Sierra修复漏洞超过60个


下一篇:linux下磁盘管理机制--LVM