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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值