標籤:
功能:
父進程建立一個子進程父進程負責讀使用者終端輸入,並寫入管道
子進程從管道接收字元流寫入另一個檔案
代碼:
#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下管道編程