Linux下管道編程

來源:互聯網
上載者:User

標籤:

功能:

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

子進程從管道接收字元流寫入另一個檔案

 

代碼:

#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 100int 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.

 

運行結果如下:

 

Linux下管道編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.