linux 文件操作函數 通過例子來解釋 父子間文件描述符共享 內存映像圖

 #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

 

內存映像圖

 進程描述符表    打開文件表(所有進程共享)          V node表(所有進程共享)

 



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1641884 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章