有名管道实现文件内容复制

mkfifo创建有名管道

写程序(将文件test1的内容都读取到管道)

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define name "FIFO"

int atomic(int from, int to, int print);

int main() {
    int fd_test, fd_pipe;
    //检测管道是否存在,如不存在则创建管道
    if (access(name, F_OK) == -1) {
        if ((mkfifo(name, 0777) != -1) && (errno == EEXIST)) {
            printf("Create fifo pipe failure\n");
            exit(0);
        }
    }
    //check open test
    if ((fd_test = open("test1", O_RDWR | O_CREAT, 0777)) < 0) {
        printf("Open or Create test1 failure\n");
        exit(0);
    }
    printf("Open test1 result %d\n", fd_test);
    //check open pipe
    if ((fd_pipe = open(name, O_RDWR)) < 0) {
        printf("Open fifopipe failure\n");
        exit(-1);
    }
    printf("Open pipe result %d\n", fd_pipe);

    /* 原子操作*/
    atomic(fd_test, fd_pipe, 1);

    close(fd_pipe);
    close(fd_test);
    return 0;
}

int atomic(int from, int to, int print) {
    //bytes in atomic write to a pipe
    int time = 0;
    int size;
    char buf[PIPE_BUF];
    size = read(from, buf, PIPE_BUF);
    for (; size > 0;) {
        if (size >= PIPE_BUF) {
            write(to, buf, PIPE_BUF);
        } else {
            write(to, buf, size);
        }
        if (print > 0) {
            printf("test1 content is \n%s", buf);
        }
        memset(buf, 0, strlen(buf));
        size = read(from, buf, PIPE_BUF);
    }
    return time;
}

读程序(将管道中的数据写入文件test2)

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define name "FIFO"

int atomic(int from, int to, int print);

int main() {
    int fd_test, fd_pipe;
    //检测管道是否存在,如不存在则创建管道
    if (access(name, F_OK) == -1) {
        if ((mkfifo(name, 0777) != -1) && (errno == EEXIST)) {
            printf("Create fifo pipe failure\n");
            exit(0);
        }
    }
    //check open test
    if ((fd_test = open("test2", O_WRONLY | O_CREAT, 0777)) < 0) {
        printf("Open or Create test2 failure\n");
        exit(0);
    }
    printf("Open test2 result %d\n", fd_test);
    //check open pipe
    if ((fd_pipe = open(name, O_RDONLY)) < 0) {
        printf("Open fifopipe failure\n");
        exit(-1);
    }
    printf("Open pipe result %d\n", fd_pipe);

    /* 原子操作*/
    atomic(fd_pipe, fd_test, 1);

    close(fd_pipe);
    close(fd_test);
    unlink(name);
    return 0;
}

int atomic(int from, int to, int print) {
    //bytes in atomic write to a pipe
    int time = 0;
    int size;
    char buf[PIPE_BUF];
    size = read(from, buf, PIPE_BUF);
    for (; size > 0;) {
        if (size >= PIPE_BUF) {
            write(to, buf, PIPE_BUF);
        } else {
            write(to, buf, size);
        }
        if (print > 0) {
            printf("test1 content is \n%s", buf);
        }
        memset(buf, 0, strlen(buf));
        size = read(from, buf, PIPE_BUF);
    }
    return time;
}

你可能感兴趣的:(Ubuntu)