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

相关文章
相关标签/搜索