#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int fd;//文件标识符
pid_t pid;//进程号
int a;//文件读取返回值
int n;//文件输入返回值
char parentbuf[1024] = {0};//父进程数据缓存区
char childbuf[1024] = {0};//子进程数据缓存区
fd = open(argv[1],O_RDWR|O_CREAT| O_TRUNC,0666);//打开文件
if(argc != 2)
{
fprintf(stderr,"文件个数必须为两个");
}
pid = fork();//打开子进程
if(pid < 0)
{
perror("fail to fork");
return -1;
}else if(pid == 0)
{
while(1)
{
memset(childbuf,0,sizeof(childbuf));
usleep(200);
a = read(fd,childbuf,sizeof(childbuf));
if(a == 0)
continue;
write(1,childbuf,sizeof(childbuf));
if(strncmp(childbuf,"quit",4) == 0)
break;
}
}else if(pid > 0)
{
while(1)
{
memset(parentbuf,0,sizeof(parentbuf));
read(0,parentbuf,sizeof(parentbuf));
n = write(fd,parentbuf,sizeof(parentbuf));
if(strncmp(parentbuf,"quit",4) == 0)
break;
lseek(fd,-n,SEEK_CUR);
}
}
close(fd);
return 0;
}