利用命名管道複製文件

1. 定義頭文件apue.h

#ifndef _APUE_H_
#define _APUE_H_

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <signal.h>
#include <sys/time.h>

void err_exit(char *m){
        perror(m);
        exit(EXIT_FAILURE);
}


#endif /* _APUE_H_ */

 

2. fifor.c, 把文件Makefile的內容讀取到管道tp中

#include "../apue.h"
int main(void){
    mkfifo("tp", 0644);
    int infd;
    infd=open("Makefile", O_RDONLY);
    if(infd==-1)
        err_exit("open error");
    int outfd;
    outfd=open("tp", O_WRONLY);
    if(outfd==-1)
        err_exit("open error");

    char buf[1024];
    int n;
    n=read(infd, buf, 1024);
    write(outfd, buf, n);
    return 0;
}

 

 

3.02fifow.c, 從管道tp中讀取數據並寫入文件Makefile2

#include "../apue.h"

int main(void){
        int fd;
        fd=open("tp", O_RDONLY);
        if (fd==-1)
                err_exit("open error");

        int infd;
        infd=open("Makefile2", O_WRONLY|O_CREAT, 0644);
        if (infd==-1)
                err_exit("open error");
        char buf[1024];
        int n;
        while ((n=read(fd, buf, 1024))>0){
                write(infd, buf, n);
        }
        return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章