您的位置:首页 > 其它

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

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

下面代码说明。

I值分离,但FD共享。

[root@localhost ~]# vim fork_descriptor.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
pid_t pid;
int fd;
int i = 1;
int status;
char *ch1 = "hello";
char *ch2 = "world";
char *ch3 = "IN";
if((fd = open("test.txt", O_RDWR | O_CREAT, 0644)) == -1)
{
perror("parent open");
exit(EXIT_FAILURE);
}
if(write(fd, ch1, strlen(ch1)) == -1)
{
perror("parent write");
exit(EXIT_FAILURE);
}
if((pid = fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(pid == 0)
{
i = 2;
printf("in child\n");
printf("i = %d\n", i);
if(write(fd, ch2, strlen(ch2)) == -1)
perror("child write");
return 0;
}
else
{
sleep(1);
printf("in parent\n");
printf("i = %d\n", i);
if(write(fd, ch3, strlen(ch3)) == -1)
perror("parent write");
wait(&status);
printf("\n");
return 0;
}
}
"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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐