我如何控制popen()创建的管道?

问题描述 投票:0回答:1

[注:我知道我可以通过使用fork甚至wait来实现我所描述的内容,但是我想了解popen的工作方式以及如何使用它在进程之间进行通信。

[我想使用popen创建一个子进程,然后在子进程中写入popen创建的管道,然后在父进程中,我从管道读取并输出消息。

这是我尝试过的:

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

#define BUFFER_SIZE 105

int main(int argc, const char * argv[])
{
    FILE* fp;
    int status;
    char buffer[BUFFER_SIZE];

    fp = popen("date", "r"); // returns `FILE *` object (the same as a "stream", I think)
    if(fp == NULL) { printf("Eroare la deschidere cu `popen()`\n");} return -1; // or `EXIT_FAILURE`

    fgets(buffer, BUFFER_SIZE, fp); // ????? is this where I am reading from the pipe? 
                                    // `popen` returns a pointer to a stream, thus is it a `FILE *` object?
                                    // As such, is `fp` also the pipe? "pipe" == "stream" == `FILE *` object ?
    printf("I have read: %s", buffer); 

    status = pclose(fp);
    if(status == -1) { printf("`Eroare la inchiderea cu popen()`\n"); return -1;} // or `EXIT_FAILURE`

return 0; // or `EXIT_SUCCESS`?
}

而且,在这种情况下,哪个管道是? fp是否既是FILE *对象又是“管道”?我可以访问fp[0]fp[1]吗?

输出:

I have read: Thu Apr 30 16:29:05 EEST 2020
c unix process pipe popen
1个回答
0
投票

我不太清楚您在这里问的是什么,所以如果这个答案不符合要求,请告诉我。

man popen确认popen返回FILE *。它不是数组;没有fp[0]fp[1]

“管道”只是一对连接的文件描述符...在父进程中可用(这是popen的返回值),在子进程中可用。从fp变量中读取时,您正在从管道的一端读取(并且子进程写入stdout时,它正在写入管道的另一端)。

© www.soinside.com 2019 - 2024. All rights reserved.