【发布时间】:2020-08-14 20:39:53
【问题描述】:
注意:我知道我可以通过使用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
【问题讨论】:
-
popen是一个标准的 C 函数。它与进程或 Unix 管道或<unistd.h>或<sys/types.h>或<sys/wait.h>无关。在内部,它可能会或可能不会使用这些 Unix 工具来实现。如果是,它将对程序员完全隐藏。 -
@n.'pronouns'm。您好,感谢您的回答!