jeans chen
we've got them by the balls

转贴自倒霉熊的博客

【linux学习笔记-2】父子进程共享文件描述符

(2009-03-02 23:03:17)

#include <stdio.h>
#include <fcntl.h>  //包含O_RDONLY等宏定义     

int main(void){

 char test;

 int fd;

 if((fd = open("test.dat",O_RDONLY))== -1)
 {
     perror("Can't open file test.dat\n");
     return 1;
 }

 printf("Open file succeed.\n");

 if(fork()==-1)
 {
  perror("Can't creat child process.\n");
  return 1;
 }
 printf("Creat child process succeed.\n");

 read(fd,&test,1);
 printf("Process ID: %ld read the character:%c\n ",(long)getpid(),test);

 close(fd);
      return 0;
}

 

test.dat内容:abcdefghijklmn

 

open函数返回的是一个整型的文件描述符信息,该文件描述符也可以用于read,write,fcntl,lseek等系统函数中。

 

如果一个进程打开了一个文件以后,创建子进程,子进程会继承父进程的环境和上下文中的大部分内容,包括文件描述符。此时父子进程享有相同的文件偏移量,执行相同的程序读取文件中的字符。程序执行结果是随机的,可能是父进程先读,产生一个偏移,再由子进程读其相邻字符,也可能结果相反。

 

以下是该程序的一种执行结果:

root@gaolu-desktop:/home/gaolu#
root@gaolu-desktop:/home/gaolu# gcc -o fork_file fork_file.c
root@gaolu-desktop:/home/gaolu#
root@gaolu-desktop:/home/gaolu#
root@gaolu-desktop:/home/gaolu#
root@gaolu-desktop:/home/gaolu#
root@gaolu-desktop:/home/gaolu# ./fork_file
Open file succeed.
Creat child process succeed.
Process ID: 6197 read the character:a 

    //子进程先读到字符a
Creat child process succeed.
Process ID: 6196 read the character:b

posted on 2013-11-19 18:02  jeans chen  阅读(502)  评论(0编辑  收藏  举报