Linux-证明子进程从父进程处拷贝了文件描述符

来源:互联网 发布:三钻淘宝店值多少钱 编辑:程序博客网 时间:2024/04/28 04:12

今天做了个小实验,证明子进程从父进程那拷贝了文件描述符,很简单,不要笑啊~

#include<sys/types.h>#include<unistd.h>#include<sys/stat.h>#include<fcntl.h>#include<stdio.h>#include<stdlib.h>#include<string.h>int main(void){pid_t pid;int fd1,temp;char buf[20];fd1=open("a.txt",O_RDWR|O_APPEND,0600);if(fd1<0){perror("parent open:");exit(1);}if((pid=fork())>0){sprintf(buf,"i am parent");if((temp=write(3,buf,strlen(buf)))<0){perror("parent error:");}else{printf("parent wirte success");fflush(stdout);}}else if(pid==0){sprintf(buf,"i am child");if((temp=write(3,buf,strlen(buf)))<0){perror("child error:");}else{printf("childe write success");fflush(stdout);}}}
注意我直接使用的是3来写入,这样就能证明已经打开了文件描述符为3的文件。(open()会打开最小的未使用的文件描述符,也就是3)。

原创粉丝点击