从execlp()返回

时间:2014-02-18 05:35:50

标签: c process exec pipe

我有一个程序,我想从子进程中对文件中的第一列进行排序,并将输出返回到父进程。如何从execlp中检索响应并打印出来?以下是我到目前为止的情况:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define WRITE 1
#define READ 0

int main(int argc, char **argv)
{
    int i, k;
    int p1[2], p2[2];

    int p1[2], p2[2];
    pid_t childID;

    if (pipe(p1) < 0 || pipe(p2) < 0) {
        perror("pipe");
        exit(0);
    }

    childID = fork();

    if (childID < 0) {      
        perror("fork");
        exit(0);
    }
    else if (childID == 0){                                 
        close(p1[WRITE]);
        close(p2[READ]);

        dup2(p1[READ], STDIN_FILENO);
        close(p1[READ]);
        dup2(p2[WRITE], STDOUT_FILENO);
        close(p2[WRITE]);

        execlp("sort", "-k1", "-n", "temp.txt", (char *)NULL);
        perror("exec");
        exit(0);
    }
    else {                                                  
        //parent process
        //Not sure how to get response from exec


    }
}

1 个答案:

答案 0 :(得分:0)

调用execlp()后,当前进程的内存映像将由被调用的progame 替换,因此您无法通过返回值获得所需内容。你可以做的是让子进程将结果写入某个地方,例如临时文件或管道,父进程从这个地方读取结果。

在父进程和子进程之间正确设置管道连接之后,可以在其stdout中编写子进程的结果,并从其stdin中读取父进程中的结果。

这样的事情:

else if (childID == 0){                                 
    close(p1[READ]);

    dup2(p1[WRITE], STDOUT_FILENO);
    close(p1[WRITE]);

    execlp("sort", "-k1", "-n", "temp.txt", (char *)NULL);
    perror("exec");
    exit(0);
}
else {                                                  
    close(p1[WRITE]);

    dup2(p1[READ], STDIN_FILENO);
    close(p1[READ]);

    while (scanf("%ms ", &l) != EOF) {
        printf("%s\n", l);
        free(l);
    }
}

以下是完整代码:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define WRITE 1
#define READ 0

int main(int argc, char **argv)
{
    int p1[2];
    char *l;

    pid_t childID;

    if (pipe(p1) < 0) {
        perror("pipe");
        exit(0);
    }

    childID = fork();

    if (childID < 0) {      
        perror("fork");
        exit(0);
    }
    else if (childID == 0){                                 
        close(p1[READ]);

        dup2(p1[WRITE], STDOUT_FILENO);
        close(p1[WRITE]);

        execlp("sort", "-k1", "-n", "temp.txt", (char *)NULL);
        perror("exec");
        exit(0);
    }
    else {                                                  
        close(p1[WRITE]);

        dup2(p1[READ], STDIN_FILENO);
        close(p1[READ]);

        while (scanf("%ms ", &l) != EOF) {
            printf("%s\n", l);
            free(l);
        }
    }

    return 0;
}

测试文件temp.txt

$ cat temp.txt
a
e
b
d
f
c

试运行结果:

$ ./a.out 
a
b
c
d
e
f