FORK()子进程对父进程打开的文件描述符的处理
2013-04-05 10:18
274 查看
总的来说,子进程将复制父亲进程的数据段,BSS段,代码段,堆空间,栈空间和文件描述符。而对于文件技术符关联内核文件表项(即STRUCT FILE结构),则是采取了共享的方式。
下面代码说明。
I值分离,但FD共享。
结果:
[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
下面代码说明。
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
相关文章推荐
- fork 子进程不继承父进程打开的文件描述符
- fork()子进程与父进程之间的文件描述符问题
- fork - 子进程在复制父进程的信号处理方式
- 《深入理解linx内核》学习笔记3---子进程共享父进程打开的文件描述符
- 当一个进程打开的文件描述符达到了上限,这时有新连接到来的sockt 如何处理?
- fork()子进程与父进程之间的文件描述符问题
- fork()子进程与父进程之间的文件描述符问题 www.educity.cn/linux/1241859.html
- fork()子进程与父进程之间的文件描述符问题
- fork 和 exec 对子进程继承父进程处理信号处理函数的影响
- fork exec对子进程继承父进程信号处理机制的影响--APUE
- 父进程和子进程关于数据和文件描述符的继承的理解
- php使用fork来创建进程,并使用多进程处理对列
- Linux查看进程打开多少文件描述符命令-lsof
- fork之后父子进程的文件描述符
- TCP编程中,在server端调用fork创建子进程,在子进程中接收/处理外部数据。
- 子进程会继承父进程用户id,用户组id,用户信息,文件描述符,数据段,堆栈,当前工作目录,创建文件权限,信号处理方式,进程组号,会话期号。
- 多进程 fork之后父子进程 对文件描述符的作用
- linux命令之修改系统允许进程打开文件描述符限制-ulimit
- C++实现的两个进程,父进程处理SIGUSR2,子进程处理SIGUSR1
- Linux进程fork execu之数据和文件描述符的继承