点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <string.h>
-
#include <errno.h>
-
#include <stdlib.h>
-
#include <sys/types.h>
-
#include <sys/stat.h>
-
#include <fcntl.h>
-
#include <unistd.h>
-
-
#define N 100
-
-
int main(int argc, const char *argv[])
-
{
-
char buf[N] = {0};
-
int n = 0;
-
int fd = 0;
-
pid_t pid = 0;
-
-
if(argc < 2)
-
{
-
fprintf(stderr,"Usage %s filename.\n",argv[0]);
-
exit(EXIT_FAILURE);
-
}
-
-
//fork之前先打开文件,父子进程共享文件表项
-
if((fd = open(argv[1],O_RDWR)) < 0)
-
{
-
fprintf(stderr,"Fail to open %s : %s\n",argv[1],strerror(errno));
-
exit(EXIT_FAILURE);
-
}
-
-
//创建新进程
-
if((pid = fork()) < 0)
-
{
-
perror("Fail to fork");
-
exit(EXIT_FAILURE);
-
}
-
-
else if(pid >0)//parent
-
{
-
printf("Father pid is: %d\t",getpid());
-
printf("fd = %d\t",fd);
-
-
n = read(fd,buf,sizeof(buf) - 1);//长度减一是为了最后已给字符填充'\0',以便于printf能正常打印输出
-
-
lseek(fd,-n,SEEK_CUR);//当读到n个字符的时候,文件的offset值增加了n,为了从头输出文件内容,所以重写定位。
-
buf[n] = '\0';
-
printf("read %d : %s",n,buf);
-
-
sleep(1);
-
}
-
-
else //child
-
{
-
printf("child pid is: %d\t",getpid());
-
printf("fd = %d\t",fd);
-
-
n = read(fd,buf,sizeof(buf) - 1);
-
lseek(fd,-1,SEEK_CUR);
-
buf[n] = '\0';
-
-
printf("read %d : %s",n,buf);
-
-
}
-
-
close(fd);
-
-
return 0;
- }
点击(此处)折叠或打开
-
litong@ltubuntu:~/exericse$ ./a.out test.txt
-
Father pid is: 3121 fd = 3 read 23 : 1234567890abcdefghijkl
- child pid is: 3122 fd = 3 read 23 : 1234567890abcdefghijkl