日期:2014-05-16  浏览次数:20641 次

命名管道的通信效率的测试
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("tic