How to use popen?

你。 提交于 2019-12-24 07:29:16

问题


I'm trying to do inter process communication with stdin and stdout. The Posix function I found is popen, but I failed to write a working sample code. Please help me get this work.

<edit1>
Do I have to use dup? I can see some examples found with Google using it. But the Linux manual of dup really does not help me understanding how to use that.
</edit1>

a.c

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

int main(void){
    char *s;

    for(;;){
        scanf("%ms",&s);
        printf("%s\n",s);
        if(!strcmp(s,"quit")){
            free(s);
            printf("bye~\n");
            exit(EXIT_SUCCESS);
        }
        free(s);
    }
}

b.c

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

int main(void){
    FILE *fRead;
    FILE *fWrite;
    char *s;
    int i;

    fRead=popen("~/a.out","r");
    fWrite=popen("~/a.out","w");
    for(i=1;i<=10;++i){
        fprintf(fWrite,"%d",i);
        fscanf(fRead,"%ms",&s);
        printf("%s\n",s);
        free(s);
    }
}

回答1:


As defined by POSIX, Pipes are a unidirectional communication mechanism — they work in one direction only. In order to redirect both standard input and standard output, you need to create two pipes — and the popen function cannot do that.

While slightly less convenient, it is not difficult to achieve what you want by using directly the system calls fork, pipe, dup2 and exec:

rc = pipe(p1);
if(rc < 0) ...
rc = pipe(p2);
if(rc < 0) ...

rc = fork();
if(rc < 0) {
    ...
} else if(rc == 0) {
    /* child */
    close(p1[0]);
    close(p2[1]);
    dup2(p1[1], 1);
    dup2(p2[0], 0);
    execlp(...);
    exit(1);
} else {
    /* parent */
    close(p1[1]);
    close(p2[0]);
    ...
}

There are other solutions ­— you could use the socketpair system call to avoid the need for two pipes, or even use Unix domain sockets directly.



来源:https://stackoverflow.com/questions/30259086/how-to-use-popen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!