c - How to use popen? -


i'm trying inter process communication stdin , stdout. posix function found popen, failed write working sample code. please me work.

<edit1>
have use dup? can see examples found google using it. linux manual of dup not me understanding how 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);     } } 

as defined posix, pipes unidirectional communication mechanism — work in 1 direction only. in order redirect both standard input , standard output, need create 2 pipes — , popen function cannot that.

while less convenient, not difficult achieve want using directly system calls fork, pipe, dup2 , 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 other solutions ­— use socketpair system call avoid need 2 pipes, or use unix domain sockets directly.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -