您的位置:首页 > 运维架构 > Linux

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

2013-05-28 10:56 162 查看
今天做了个小实验,证明子进程从父进程那拷贝了文件描述符,很简单,不要笑啊~

#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)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: