命名管道的通信效率的测试
write.c#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <fcntl.h>#include <limits.h>#include <sys/types.h>#include <sys/stat.h>#include <pthread.h>#include <time.h>#define FIFO_NAME "/tmp/my_fifo"#define BUFFER_SIZE PIPE_BUF //4096#define TEN_MEG (1024 * 1024 * 1) //决定每次循环传输数据的大小void* thread_tick(void* arg) //用来测试管道会不会阻塞进程{ printf("hello, world!\n"); sleep(1);}void* thread_write(void* arg){ int pipe_fd; int res; int bytes_sent = 0; char buffer[BUFFER_SIZE ]; int count=0; //决定总共循环多少次 if (access(FIFO_NAME, F_OK) == -1) { res = mkfifo(FIFO_NAME, 0777); if (res != 0) { fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME); exit(EXIT_FAILURE); } } while(count<1){ printf("write: Process %d opening FIFO O_WRONLY\n", getpid()); pipe_fd = open(FIFO_NAME, O_WRONLY); printf("write: Process %d result %d \n", getpid(), pipe_fd); if (pipe_fd != -1) { while(bytes_sent < TEN_MEG) { res = write(pipe_fd, buffer, BUFFER_SIZE); if (res == -1) { fprintf(stderr, "Write error on pipe\n"); exit(EXIT_FAILURE); } bytes_sent += res; } (void)close(pipe_fd); } else { exit(EXIT_FAILURE); } printf("write: Process %d finished , count =%d\n", getpid(),count); count++; }}int main(){ pthread_t write; pthread_t tick; int resw, rest ; rest = pthread_create(&tick, NULL, thread_tick, 0); if(rest != 0) { perror("tick thread creation failed\n"); exit(EXIT_FAILURE); } resw = pthread_create(&write, NULL, thread_write, 0); if(resw != 0) { perror("write thread creation failed\n"); exit(EXIT_FAILURE); } resw = pthread_join(write, 0); rest = pthread_join(tick, 0); return 0;}read.c#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <fcntl.h>#include <limits.h>#include <sys/types.h>#include <sys/stat.h>#define FIFO_NAME "/tmp/my_fifo"#define BUFFER_SIZE PIPE_BUF //4096int main(){ int pipe_fd; int res; char buffer[BUFFER_SIZE ]; int bytes_read = 0; int count =0; memset(buffer, '\0', sizeof(buffer)); while(count < 1){ printf("read: Process %d opening FIFO O_RDONLY\n", getpid()); pipe_fd = open(FIFO_NAME, O_RDONLY); printf("read: Process %d result %d\n", getpid(), pipe_fd); if (pipe_fd != -1) { do { res = read(pipe_fd, buffer, BUFFER_SIZE); bytes_read += res; } while (res > 0); (void)close(pipe_fd); } else { exit(EXIT_FAILURE); } printf("read: Process %d finished, %d bytes read , count =%d\n", getpid(), bytes_read,count); count++; }}