tags:

views:

124

answers:

4

Can I make an anonymous stream in c? I don't want to create a new file on the file system, just have a stream that one function can fwrite to while the other can fread from it. Not c++, c.

A: 

Oops, just found it... maybe. tmpfile() returns a tmeporary FILE *

Is that the right way to do it?

Eyal
that will still create a file...
Evan Teran
+5  A: 

Maybe You're looking for pipes.

Forward Your STDOUT to the pipe.

Then the other application would read from the pipe.

#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;
}
bua
+1  A: 

Yes, tmpfile() is one way to do it. However, I believe tmpfile() is frowned upon these days due to security concerns.

So, you should use mkstemp in POSIX or tmpfile_s in Windows instead of tmpfile().

These will all still create files in the filesystem, though. They're temporary in that they "go away" when the program exits.

Another option, which doesn't create a physical file is mmap().

Coleman
A: 

If you're on Unix (or a similar OS), you want to read Beej's Guide to Unix Interprocess Communication (it's a good read no matter what your OS is).
Check it out at Beej's Guides.

In a rapid glance there I noticed a few things you could probably use with more or less work (and with the optional creation of a file/resource):

  • Pipes
  • FIFOs
  • Message Queues
  • Shared Memory Segments
  • Memory Mapped Files
  • Unix Sockets
pmg