(1)用文件IO,以读写的方式打开文件.
(2)利用fork创建子进程。父进程利用fegets从键盘输入数据,写到文件中。书写完毕后,调用lseek()定位到头部。若是用户输入“quit" ,结束输入循环。
(3)子进程循环调用read函数,读取数据。若是读到的数据是0,说明读到文件尾部,调用continue继续读。否则若是读取数据。正常数据。若是读到"quit",结束读取循环。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
char buf[1024] = {0};
int n = 0;
int fd = open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
pid_t pid;
pid = fork();
if(pid < 0){
perror("fork");
return -1;
}else if(pid > 0){
while(1){
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
n = write(fd,buf,sizeof(buf));
lseek(fd,-n,SEEK_CUR);
if(strncmp(buf,"quit",4) == 0){
break;
}
}
}else if(pid == 0){
while(1){
usleep(200);
memset(buf,0,sizeof(buf));
int count = read(fd,buf,sizeof(buf));
if(count == 0){
continue;
}
printf("Read %ld bytes:%s\n",strlen(buf),buf);
if(strncmp(buf,"quit",4) == 0){
break;
}
}
}
return 0;
}