c中的匿名流

Eya*_*yal 1 c stream

我可以在c中创建一个匿名流吗?我不想在文件系统上创建一个新文件,只需要一个函数可以写入的流,而另一个函数可以从它传播.不是c ++,c.

bua*_*bua 6

也许你正在寻找管道.

将您的STDOUT转发到管道.

然后另一个应用程序将从管道中读取.

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

#define RDR 0
#define WTR 1

char ** parseargs(char *string);

int main(void){
   char mode = 'r'; 
   char prog[50] = "/bin/ps --version";
   char **argv; 
   int p[2]; 
   pid_t pid;
   FILE *readpipe;
   int pipein, pipeout; 
   char buf; 


   /* create the pipe */
   if(pipe(p) != 0){
      fprintf(stderr, "error: could not open pipe\n");
   }

   pipein = p[RDR];
   pipeout = p[WTR];

   if((pid = fork()) == (pid_t) 0){



      close(pipein);

      dup2(pipeout, 1);
      close(pipeout);


      if(execv(argv[0], argv) == -1){
         fprintf(stderr, "error: failed to execute %s\n", argv[0]);
      }
      _exit(1);
   }

   close(pipeout);


   readpipe = fdopen(pipein, &mode);

   while(!feof(readpipe)){
      if(1 == fread(&buf, sizeof(char), 1, readpipe)){
         fprintf(stdout, "%c", buf);
      }
   }


   return 0;
}
Run Code Online (Sandbox Code Playgroud)