Linux下管道編程

功能:spa

父進程建立一個子進程父進程負責讀用戶終端輸入,並寫入管道code

子進程從管道接收字符流寫入另外一個文件blog

 

代碼:進程

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#define MAX 100

int main()
{
    int n,c = 0;
    int fd[2];
    char ch;
    pid_t pid;
    char buffer[MAX+10];

    if(pipe(fd) < 0) {                   //建立管道
        puts("管道建立失敗");
        exit(1);
    }
    pid = fork();                        //建立子進程
    if(pid < 0)
        puts("子進程建立失敗");
    else if(pid > 0) {                   //
        close(fd[0]);                    //關閉讀端口
        puts("please input what you want to say:");
        while((ch = getchar()) != '\n') {                       //讀字符串(可空格)到buffer
            if(c == MAX) { puts("buffer is fulled!"); break; }
            buffer[c++] = ch;
        }
        buffer[c] = '\0';
        write(fd[1], buffer, c);         //寫入管道
    }
    else {                               //
        close(fd[1]);                    //關閉寫端口
        n = read(fd[0], buffer, MAX);    //從管道中讀出數據,n爲讀出的字符個數
        printf("What you input is: [/home/whatbeg/hq/oshomework.txt]\n");
        int dft_fd = open("/home/whatbeg/hq/oshomework.txt", O_RDWR | O_CREAT, 0777); //打開文件,若是沒有,建立一個對三方均可讀可寫可執行的txt文件
        if(dft_fd == -1) {               //打開失敗
            puts("打開文件失敗!\n");
            exit(1);
        }
        write(STDOUT_FILENO, buffer, n); //寫到終端,方便觀測
        write(dft_fd, buffer, n);        //寫到文件
        close(dft_fd);                   //關閉文件
    }
    return 0;
}

// 'gets' is deprecated
//警告: the 'gets' function is dangerous and should not be used.

 

運行結果以下:ip

相關文章
相關標籤/搜索