#include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/wait.h> #include <sys/stat.h> #define MAXLINE 4096 #define BUFFSIZE 4096 #define FIFO1 "/tmp/fifo.1" #define FIFO2 "/tmp/fifo.2" void client(int, int), server(int, int); int main(int argc, char *argv[]) { int readfd, writefd; pid_t childpid; if((mkfifo(FIFO1, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)<0)&&(errno!=EEXIST)) { fprintf(stderr, "can't create %s\n", FIFO1); exit(-1); } if((mkfifo(FIFO2, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)<0)&&(errno!=EEXIST)) { unlink(FIFO1); fprintf(stderr, "cant't create %s\n", FIFO2); } if((childpid=fork()) < 0) { perror("fork error"); exit(-1); } else if(childpid == 0) { if((readfd=open(FIFO1, O_RDONLY, 0))<0) { fprintf(stderr, "open %s error.\n", FIFO1); exit(-1); } if((writefd=open(FIFO2, O_WRONLY, 0))<0) { fprintf(stderr, "open %s error.\n", FIFO2); exit(-1); } server(readfd, writefd); exit(0); } if((writefd=open(FIFO1, O_WRONLY, 0))<0) { fprintf(stderr, "open %s error.\n", FIFO1); exit(-1); } if((readfd=open(FIFO2, O_RDONLY, 0))<0) { fprintf(stderr, "open %s error.\n", FIFO2); exit(-1); } client(readfd, writefd); if((waitpid(childpid, NULL, 0)) == -1) { perror("waitpid error"); exit(-1); } if(close(readfd)==-1) { fprintf(stderr, "close readfd error.\n"); exit(-1); } if(close(writefd)==-1) { fprintf(stderr, "close writefd error.\n"); exit(-1); } if(unlink(FIFO1)<0) { fprintf(stderr, "delete %s error.\n", FIFO1); exit(-1); } if(unlink(FIFO2)<0) { fprintf(stderr, "delete %s error.\n", FIFO2); exit(-1); } exit(0); } void client(int readfd, int writefd) { size_t len; ssize_t n; char buff[MAXLINE]; printf("-------hello-----starting client------------\n"); if((fgets(buff, MAXLINE, stdin) == NULL) && ferror(stdin)) { perror("fgets error"); exit(-1); } printf("client ipc pathname: %s\n", buff); len = strlen(buff); if(buff[len-1] == '\n') len--; if(write(writefd, buff, len) != len) { perror("write error"); exit(-1); } while((n=read(readfd, buff, MAXLINE)) > 0) { printf("-----------------print to film----------------\n"); if (write(STDOUT_FILENO, buff, n) != n ) { perror("write error"); exit(-1); } } } void server(int readfd, int writefd) { int fd; ssize_t n; char buff[MAXLINE+1]; printf("----------------start server-------------------\n"); if((n=read(readfd, buff, MAXLINE)) == -1) { perror("read error"); exit(-1); } if(n == 0) { perror("end-of-file while reading pathname"); exit(-1); } buff[n]='\0'; printf("server IPC pathname: %s\n",buff); if((fd=open(buff, O_RDONLY)) < 0) { snprintf(buff+n, sizeof(buff)-n, ": can't open, %s\n", strerror(errno)); n=strlen(buff); if(write(writefd, buff, n) != n) { perror("write error"); exit(-1); } } else { printf("------server open file success-------\n"); while((n=read(fd, buff, MAXLINE)) > 0) { if(write(writefd, buff, n) != n) { perror("write error"); exit(-1); } } close(fd); } }