【问题标题】:Passing stdout to C program将标准输出传递给 C 程序
【发布时间】:2015-01-06 03:58:06
【问题描述】:

我试图通过玩弄它来弄清楚 C 中的管道。我想编写一个程序,从 shell 命令“cat”获取输出,将其保存为字符串,然后打印该字符串。该命令应如下所示:

cat foo.txt | ./my_prog

我在将 cat 命令的输出发送到 my_prog 时遇到问题。这是我迄今为止尝试过的。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
    int pipe_1[2];
    pid_t pid = -1;
    char catString[200];
    catString [199] = '\0';

    // dup stdout to pipe_1
    if( dup2(STDOUT_FILENO, pipe_1[1]) == -1 ){
            perror("Could not create pipe 1");
            exit(-1);
    }

    // fork a new process
    pid = fork();
    switch(pid){
    case -1:
            perror("Fork 1 failed");
            exit(-1);
    case 0: // child
            // close stdin and write stdout to the string
            close(pipe_1[0]);
            write(pipe_1[1], catString, 200);
            break;
    default: // parent
            // wait for child process to finish, close stdout, then print the string
            wait(NULL);
            close(pipe_1[1]);
            printf("Parent recieved %s\n", catString);
            break;
    }
return 0;
}

这不会打印任何东西并给我输出:

父母收到

顺便说一句,我是否正确使用了 wait() 函数?我想确保子进程在父进程执行之前完成对 catString 的写入。

【问题讨论】:

  • 如果你想在你的程序 inside 中创建一个管道(在你的情况下这没用),你应该在 pipe_1 之前调用 pipe(2) (否则没用) fork.

标签: c operating-system pipe fork system


【解决方案1】:

shell 会将cat foo.txt 的输出发送到您程序的stdin。您无需对程序内部的“管道”进行任何操作,只需以 shell 传递它的方式接受输入即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多