【问题标题】:Father-child process use pipe to talk, hangs after "execlp", why?父子进程使用管道交谈,“execlp”后挂起,为什么?
【发布时间】:2017-03-05 07:28:26
【问题描述】:

我在当前目录下有一个名为“tmp”的简单文本文件,我想“cat”这个文件然后“排序”它,我想用一个c程序来充当管道“|”所以我试着用父亲/孩子的谈话来做到这一点。

没想到,程序在“cat”之后挂了,如下所示:

#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(){
    int pipefd[2];
    pipe(pipefd);
    int& readfd=pipefd[0];
    int& writefd=pipefd[1];

    pid_t pid=fork();
    if(pid==0){//child
        dup2(STDIN_FILENO,writefd);
        close(readfd);
        execlp("cat","cat","tmp",NULL);
        printf("child cat ends\n");
        exit(0);
    }else{//father
        dup2(STDOUT_FILENO,readfd);
        close(writefd);
        execlp("sort","sort",NULL);
        printf("father sort ends\n");
    }
    int status;
    wait(&status);
    printf("father exists\n");
    return 0;
}

g++编译和运行这个文件,在“cat”tihis文件之后,我什至没有看到“child cat ends”,它只是挂起。

问题出在哪里,如何解决? 谢谢

【问题讨论】:

    标签: linux process pipe fork freeze


    【解决方案1】:

    1) dup2 中的参数顺序不正确。看dup2

    2) dup2 的参数(stdin/stdout)不正确。

    3) exec() 系列函数将进程映像替换为新映像。所以该调用之后的代码不会运行(除非 exec() 失败),所以我删除了这些。

    代码如下:

     #include <stdlib.h>
     #include <stdio.h>
     #include <unistd.h>
    
     int main(){
       int pipefd[2];
       pipe(pipefd);
       int& readfd = pipefd[0];
       int& writefd = pipefd[1];
    
       pid_t pid = fork();
    
       if(pid == 0){ //child
         dup2(writefd, 1);  // 1 is STDOUT_FILENO -- cat already has input -- needs output
         close(readfd);
         execlp("cat","cat","tmp.txt", NULL);
         perror("execlp() failed in child");
    
       }else{ //father
         dup2(readfd, 0); // 0 is STDIN_FILENO -- because sort needs input!
         close(writefd);
         execlp("sort","sort", NULL);
         perror("execlp() failed in parent");
       }
       return 0;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多