C 管道到另一个程序的 STDIN

标签 c pipe

我几乎看不懂管道的手册页,所以我需要帮助理解如何在外部可执行文件中获取管道输入。

我有 2 个程序: main.o & log.o

我写了 main.o fork 。这是它在做什么:

  • 父叉将数据通过管道传送到子叉
  • 子叉将执行 log.o

  • 我需要用于将主管道连接到 的 STDIN 的子叉log.o

    log.o 只需将带有时间戳的 STDIN 和日志记录到文件中即可。

    我的代码由来自我不记得的各种 StackOverflow 页面的一些代码和管道的手册页组成:
    printf("\n> ");
    while(fgets(input, MAXINPUTLINE, stdin)){
       char buf;
       int fd[2], num, status;
       if(pipe(fd)){
          perror("Pipe broke, dood");
          return 111;
       }
       switch(fork()){
       case -1:
          perror("Fork is sad fais");
          return 111;
    
       case 0: // Child
          close(fd[1]); // Close unused write end
          while (read(fd[0], &buf, 1) > 0) write(STDOUT_FILENO, &buf, 1);
    
          write(STDOUT_FILENO, "\n", 1);
          close(fd[0]);
          execlp("./log", "log", "log.txt", 0); // This is where I am confused
          _exit(EXIT_FAILURE);
    
       default: // Parent
          data=stuff_happens_here();
          close(fd[0]); // Close unused read end
          write(fd[1], data, strlen(data));
          close(fd[1]); // Reader will see EOF
          wait(NULL); // Wait for child
       }
       printf("\n> ");
    }
    

    最佳答案

    我想这就是你要做的:
    1.主叉,父通过管道将消息传递给子。
    2. child 从管道接收消息,将消息重定向到 STDIN,执行日志。
    3.记录从STDIN接收消息,做一些事情。

    做到这一点的关键是dup2重定向文件描述符,从管道到标准输入。

    这是修改后的简单版本:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <errno.h>
    
    int main(int argc, char *argv[]) {
        int fd[2];
        char buf[] = "HELLO WORLD!";
        if(pipe(fd)){
          perror("pipe");
          return -1;
        }
        switch(fork()){
            case -1:
                perror("fork");
                return -1;
            case 0:
                // child
                close(fd[1]);
                dup2(fd[0], STDIN_FILENO);
                close(fd[0]);
                execl("./log", NULL);
            default:
                // parent
                close(fd[0]);
                write(fd[1], buf, sizeof(buf));
                close(fd[1]);
                wait(NULL);
        }
        printf("END~\n");
        return 0;
    }  
    

    关于C 管道到另一个程序的 STDIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20187734/

    相关文章:

    将字符串(char)转换为数组(int)

    c - 为什么减去字符实现的行为是特定的?

    objective-c - 音频缓冲区代码中的内存不断增长

    const 文本变量声明 C

    c - 将 fgets() 与管道一起使用

    C Atmega328P String 到 Int 转换 block RX 中断

    Linux fifo(命名管道)O_NONBLOCK 中断管道

    c - 正确的 fork() 和 pipe() 用于有多个 child 的单亲。我该怎么做?

    c - 如何在打开/写入功能中实现超时

    ffmpeg - 使用 ffmpeg 将直播从 m3u8 录制到管道会导致视频没有音频