代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
// FILE *fp = fopen(argv[1],"a+");
// if(fp == NULL)
// {
// perror("Fail to fopen");
// return -1;
// }
int fd;
fd = open(argv[1],O_RDWR | O_CREAT | O_TRUNC);
char ch[1024] = "";
// char *getin = NULL;
size_t size = 0;
if(fd < 0)
{
perror("Fail to open");
return -1;
}
pid_t pid ;
pid = fork();
if(pid < 0)
{
perror("Fail to fork");
return -1;
}
else if(pid == 0)
{
usleep(200);
// sleep(1);
while(1)
{
memset(ch,0,sizeof(ch));
size = read(fd,ch,sizeof(ch));
if(size == 0)
{
continue;
}
printf("Child read %ld bytes\t:%s\n",size,ch);
if(strncmp(ch,"quit",4) == 0)
{
break;
}
// getin = fgets(ch,sizeof(ch),stdin);
// if(/*fgets(ch,sizeof(ch),stdin) == NULL ||*/ strncmp(ch,"quit",4) == 0)
// {
// break;
// }
// fputs(ch,fp);
// write(STDIN_FILENO,ch,sizeof(ch));
}
// lseek(fd,0,SEEK_SET);
// printf("Parent write %ld bytes\t:%s\n",size,ch);
}
else if(pid > 0)
{
while(1)
{
memset(ch,0,sizeof(ch));
fgets(ch,sizeof(ch),stdin);
size = write(fd,ch,strlen(ch)-1);
lseek(fd,-size,SEEK_CUR);
if(strncmp(ch,"quit",4) == 0)
{
break;
}
}
// if()
// {
// return -1;
// }
// size = read(fd,ch,sizeof(ch));
}
close(fd);
// fclose(fp);
// while(1);
return 0;
}
程序运行结果: