//pipe/mainfifo.с #include #include #include #include #include #include #include #include #include #define FIFO1 "/tmp/fifo.1" #define FIFO2 "/tmp/fifo.2" #define MAXLINE 180 #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) void client(char *, char *), server(char *, char *); int main(int argc, char **argv) { FILE *readfd, *writefd; pid_t childpid; /* создание двух FIFO, если существуют - OK */ if ((mkfifo(FIFO1, FILE_MODE) < 0) && (errno != EEXIST)) { printf("can't create %s", FIFO1); exit(-1); } if ((mkfifo(FIFO2, FILE_MODE) < 0) && (errno != EEXIST)) { unlink(FIFO1); printf("can't create %s", FIFO2); exit(-2); } if ( (childpid = fork()) == 0) { /* child */ //readfd = fopen(FIFO1, "r"); //writefd = fopen(FIFO2, "w"); server(FIFO1, FIFO2); exit(0); } /* родительский процесс */ //writefd = fopen(FIFO1, "w"); //readfd = fopen(FIFO2, "r"); client(FIFO2, FIFO1); waitpid(childpid, NULL, 0);/*ожидание завершения дочернего процесса */ //fclose(readfd); //fclose(writefd); unlink(FIFO1); unlink(FIFO2); exit(0); } void client(char * read, char * write) { size_t len; ssize_t n; FILE *readfd, *writefd; char buff[MAXLINE]; //printf("Descriptors: read:%p, write:%p\n",readfd,writefd); /* получение полного имени файла */ printf("Client wait filename:"); //fgets(buff, MAXLINE, stdin); gets(buff); len = strlen(buff); /* fgets() гарантирует завершающий нулевой байт */ printf("Client sending %s\n",buff); writefd=fopen(write,"w"); fputs(buff,writefd); //n=fprintf(writefd, "%s",buff); printf("Client wait responce!\n"); fclose(writefd); readfd=fopen(read,"r"); printf("Responce:\n"); /* считывание из канала, вывод в stdout */ while //( fgets(buff,80,readfd)) ((fgets(buff,MAXLEN,readfd))) printf("%s",buff); } void server(char * read, char * write) { FILE *readfd, *writefd, *fd; ssize_t n; char buff[MAXLINE+1]; printf("Server wait...\n"); readfd=fopen(read,"r"); //printf("Descriptors: read=%p, write=%p\n", readfd, writefd); /* получение полного имени из канала IPC */ fgets(buff,MAXLINE,readfd); printf("Server get %s.",buff); n=strlen(buff); printf("Get %d bytes\n",n); fclose(readfd); writefd=fopen(write,"w"); buff[n] = '\0'; /* полное имя завершается 0 */ fd = fopen(buff, "r"); printf("Desc=%p\n", fd); if (!fd) { /* 4error must tell client */ snprintf(buff+n, sizeof(buff)-n,": can't open %s\n",strerror(errno)); //n = strlen(buff); printf("Sending error:%s\n",buff); fprintf(writefd, "%s",buff); } else { /* файл успешно открыт и копируется в канал */ printf("Server sending responce\n"); while ( (fgets(buff, MAXLINE,fd)) > 0) { fprintf(writefd,"%s",buff); //printf("Server sent %d bytes\n",n); } fclose(fd); fclose(writefd); } }