#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
void cyg_error(char * msg)
{
printf("%s:%s/n",msg,strerror(errno));
exit(0);
}
//构建自己的安全的fork函数
pid_t myFork()
{
pid_t mypid;
if ((mypid = fork())<0)
{
cyg_error("fork");
}
return mypid;
}
void fdInFork()
{
int fd;
char c;
int size;
int pid;
fd = open("test.txt",O_RDONLY,0); //打开一个共享文件描述符
//test.txt文件的内容 "abcdefghijklmn"
if((pid = myFork())==0) //子进程
{
size = read(fd,&c,1);
printf("_________the character is %c/n",c);
lseek(fd,3,1);
size = read(fd,&c,1);
printf("_________the character is %c/n",c);
size = read(fd,&c,1);
printf("~~~~~~~~~the character is %c/n",c);
close(fd);//子进程中关闭了该描述符,但是共享文件操作的痕迹还是被保留了
size = read(fd,&c,1);//会返回-1,因为已经关掉
printf("size %d_________the character is %c/n",size,c);
exit(0);
}
//waitpid(-1,NULL,0);//等待子进程结束
wait(NULL);
size = read(fd,&c,1);//接着子进程的游标位置开始读
printf("########the character is %c/n",c);
close(fd);//当文件的所有引用都关掉时,内存文件映像才被回收
printf("###the character is %c/n",c);
}
函数执行结果
_________the character is a
_________the character is e
~~~~~~~~~the character is f
size -1_________the character is f
########the character is g
###the character is g
内存映像图

本文通过实现一个安全的fork函数并展示父子进程间如何共享文件描述符,解释了进程间文件描述符的独立性和文件映射内存的共享机制。通过具体的C代码示例,演示了在父子进程中读取同一文件的不同部分,并展示了关闭文件描述符对其他进程的影响。
200

被折叠的 条评论
为什么被折叠?



