#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int p = open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
char parent_buf[1024]={0};
char child_buf[1]={0};
pid_t pid = fork();
if(pid < 0){
perror("Fail to fork");
return -1;
}
else if(pid > 0)
{
while(1){
read(STDIN_FILENO,parent_buf,sizeof(parent_buf));
if(strncmp(parent_buf,"quit",4)==0){
break;
}
write(p,parent_buf,sizeof(parent_buf));
}
close(p);
}
else if(pid == 0)
{
usleep(200);
lseek(p,0,SEEK_SET);
ssize_t n;
while(1){
n = read(p,child_buf,sizeof(child_buf));
if(n == 0){
break;
}
write(STDOUT_FILENO,child_buf,sizeof(child_buf));
}
close(p);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int fd = open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
if(fd==-1){
perror("Fail to fopen");
return -1;
}
int a=0;
char buf[1024]={0};
char child_buf[1024]={0};
while(1){
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
write(fd,buf,sizeof(buf));
if(strncmp(buf,"quit",4) == 0){
break;
}
pid_t p = fork();
if(p<0){
perror("Fail to fork");
return -1;
}
if(p == 0){
lseek(fd,0,SEEK_SET);
while(1){
usleep(200);
memset(child_buf,0,sizeof(child_buf));
ssize_t n;
n = read(fd,child_buf,sizeof(child_buf));
if(n == 0){
continue;
}
if(strncmp(child_buf,"quit",4)==0){
break;
}
write(STDOUT_FILENO,child_buf,strlen(child_buf));
}
}
}
close(fd);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int fd = open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
if(fd==-1){
perror("Fail to fopen");
return -1;
}
int a=0;
char buf[1024]={0};
char child_buf[1024]={0};
pid_t p = fork();
if(p < 0){
perror("Fail to fork");
return -1;
}else if(p > 0){
while(1){
// lseek(fd,0,SEEK_END);
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
write(fd,buf,strlen(buf));
if(strncmp(buf,"quit",4) == 0){
break;
}
lseek(fd,(-1)*strlen(buf),SEEK_CUR);
}
// close(fd);
}else if(p == 0){
// lseek(fd,0,SEEK_SET);
while(1){
usleep(200);
memset(child_buf,0,sizeof(child_buf));
ssize_t n;
n = read(fd,child_buf,sizeof(child_buf));
// printf("%ld\n",n);
if(n == 0){
continue;
}
if(strncmp(child_buf,"quit",4)==0){
break;
}
write(STDOUT_FILENO,child_buf,strlen(child_buf));
}
}
close(fd);
return 0;
}