zoukankan      html  css  js  c++  java
  • 管道的字节流特性

    #include <stdio.h>
    #include <sys/wait.h>
    #include <unistd.h>
    #include <string.h>
    
    #define BUF_SIZE 10
    
    int main(int argc, char *argv[]) {
        int pfd[2];
        char buf[BUF_SIZE];
        ssize_t numRead;
    
        if(argc != 2 || strcmp(argv[1], "--help") == 0) {
            printf("%s string
    ", argv[0]);
            return -1;
        }
    
        if(pipe(pfd) == -1) {
            fprintf(stderr, "pipe error.");
            return -1;
        }
    
        switch(fork()) {
        case -1:
            fprintf(stderr, "fork() error.");
            break;
        case 0:
            if(close(pfd[1]) == -1) {
                fprintf(stderr, "close error.");
                return -1;
            }
            for(;;) {
                numRead = read(pfd[0], buf, BUF_SIZE);
                if(numRead == -1) {
                    fprintf(stderr, "read error.");
                    return -1;
                }
                if(numRead == 0) {
                    break;
                }
                if(write(STDOUT_FILENO, buf, numRead) != numRead) {
                    fprintf(stderr, "write error");
                    return -1;
                }
            }
            write(STDOUT_FILENO, "
    ", 1);
            if(close(pfd[0]) == -1) {
                fprintf(stderr, "close error");
                return -1;
            }
            break;
        default:
            if(close(pfd[0]) == -1) {
                fprintf(stderr, "close error.");
                return -1;
            }
            if(write(pfd[1], argv[1], strlen(argv[1])) != strlen(argv[1])) {
                fprintf(stderr, "write error.");
                return -1;
            }
            if(close(pfd[1]) == -1) {
                fprintf(stderr, "close error.");
                return -1;
            }
            wait(NULL);
            break;
        }
        return 0;
    }
  • 相关阅读:
    事件总线demo
    软件架构分类(转载)
    ASP.NET MVC 使用 Datatables (2)
    ASP.NET MVC 使用 Datatables (1)
    查看win10的激活信息和版本号
    2016年工作计划
    通俗粗暴的事件委托理解
    matplotlib系列——条形图
    matplotlib系列——折线图
    使用pip安装python模块和包
  • 原文地址:https://www.cnblogs.com/donggongdechen/p/15010241.html
Copyright © 2011-2022 走看看