管道问题(断管)

时间:2014-02-16 07:37:00

标签: c++ unix pipe

给出这种格式的命令:

cat < inputfile.txt | tee outputfile.txt

我正在尝试将inputfile.txt写入管道,然后从管道中读取outputfile.txt,并且我已经编写了以下函数来执行此操作:

void piperead(char** input, int* fd, int start) {

    dup2(fd[0], 0);
    close(fd[1]);
    execl("usr/bin/tee", "usr/bin/tee", input[start + 1], NULL);

}

void pipewrite(char** input, int* fd, int start, int end) {

    dup2(fd[1], 1);
    close(fd[0]);
    execl("usr/bin/cat", "usr/bin/tee", input[start + 2], NULL);

}

void dopiping(char** input, int start, int end) {

    int fd[2];
    if (pipe(fd) == -1) {
        cout << "Error: Pipe failed." << endl;
        exit(1);
    }
    int pid = fork();
    switch(pid = fork()) {        
        case 0:
            piperead(input, fd, start, end);
        default:
            pipewrite(input, fd, end + 1);        
        case -1:
            exit(1);
    }


}

我已将命令转换为c_strings数组(让我们称之为cmdarray),然后我调用dopiping(cmdarray,0,3)。程序到达该行的那一刻:

 dup2(fd[1], 1)

程序终止,因为程序收到了SIGPIPE。为什么我的管道坏了,我该如何解决?

1 个答案:

答案 0 :(得分:1)

从逻辑上看这个

  • SIGPIPE被传递给对封闭或管道/套接字执行write()的进程。
  • 因此,您创建的管道的读数侧必须已关闭。
  • 执行fd[0]
  • 后,您的代码未关闭dup2()
  • 所以看起来子进程正在退出。
  • 我猜想execl()失败了 - 你应该尝试指定&#34; / usr / bin / tee&#34; (完整路径不是相对路径)
  • 或您的tee失败 - 需要确保input[start+1]指向表示有效文件路径的以空字符结尾的字符串。
相关问题