• I/O重定向和管道


      dup,dup2
    目标 复制一个文件描述符
    头文件 #include <unistd.h>
    函数原型

    newfd = dup(oldfd);

    newfd = dup2(oldfdm, newfd);

    参数

    oldfd需要复制的文件描述符

    newfd复制oldfd后得到的文件描述符

    返回值

    -1    发生错误

    newfd    新的文件描述符

      pipe
    目标 创建管道
    头文件 #include <unistd.h>
    函数原型

    result = pipe(int array[2]);

    参数

    array包含两个int类型数据的数组

    返回值

    -1  发生错误

    0         成功

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 #include <unistd.h>
     5 #include <fcntl.h>
     6 
     7 int main()
     8 {
     9     int len, i, apipe[2];
    10     char buf[BUFSIZ];
    11 
    12     if (pipe(apipe) == -1)
    13     {
    14         perror("could not make pipe");
    15         exit(1);
    16     }
    17 
    18     printf("Got a pipe! It is file descriptors: {%d %d}
    ", apipe[0], apipe[1]);
    19 
    20     int infd = open("/etc/passwd", O_RDONLY);
    21     dup2(infd, 0);
    22     int outfd = open("userlist", O_WRONLY);
    23     dup2(outfd, 1);
    24 
    25 
    26     while (fgets(buf, BUFSIZ, stdin))
    27     {
    28         len = strlen(buf);
    29         if (write(apipe[1], buf, len) != len)
    30         {
    31             perror("writing to pipe");
    32             break;
    33         }
    34 /*
    35         for (i = 0; i < len; i++)
    36         {
    37             buf[i] = 'X';
    38         }
    39 */
    40         len = read(apipe[0], buf, BUFSIZ);
    41         if (len == -1)
    42         {
    43             perror("reading from pipe");
    44             break;
    45         }
    46         if (!fputs(buf, stdout))
    47         {
    48             perror("writing to stdout");
    49             break;
    50         }
    51     }
    52 
    53     return 0;
    54 }
  • 相关阅读:
    数据加密标准(DES)详解(附源码)
    《ProGit》阅读笔记
    版本管理——Git和SVN的介绍及其优缺点
    jQuery-动画
    ajax与jsonp中的几个封装函数
    关于ajax
    js基础——数组的概念及其方法
    js实现放烟花效果——点击处会从下向上升起烟花
    js实现——鼠标移动时跟随着一连的小图片
    BFC的作用及其应用
  • 原文地址:https://www.cnblogs.com/bournet/p/4037643.html
Copyright © 2020-2023  润新知