zoukankan      html  css  js  c++  java
  • Linux下管道编程

    功能:

    父进程创建一个子进程父进程负责读用户终端输入,并写入管道

    子进程从管道接收字符流写入另一个文件

    代码:

    #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()) != '
    ') {                       //读字符串(可空格)到buffer
                if(c == MAX) { puts("buffer is fulled!"); break; }
                buffer[c++] = ch;
            }
            buffer[c] = '';
            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]
    ");
            int dft_fd = open("/home/whatbeg/hq/oshomework.txt", O_RDWR | O_CREAT, 0777); //打开文件,如果没有,创建一个对三方都可读可写可执行的txt文件
            if(dft_fd == -1) {               //打开失败
                puts("打开文件失败!
    ");
                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.

    运行结果如下:

  • 相关阅读:
    《自己动手写操作系统》:开发环境配置心得
    sip.conf配置详情
    MySQL字符串中数字排序的问题
    Asterisk iax错误提示
    Python 快速入门
    C# winfrom 导出word
    SetWindowsHookEx函数参数详解
    Ubuntu Linux系统下轻松架设nginx+php服务器应用
    TShockwaveFlash的使用
    检讨
  • 原文地址:https://www.cnblogs.com/whatbeg/p/4461725.html
Copyright © 2011-2022 走看看