#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
内存映像图
Trackback: http://tb.blog.youkuaiyun.com/TrackBack.aspx?PostId=1641884