簡體   English   中英

從execlp()獲得回報

[英]Getting return from execlp()

我有一個程序,希望對子進程中文件的第一列進行排序,然后將輸出返回給父進程。 如何從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


    }
}

調用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM