LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Opening a File by using a named pipe (https://www.linuxquestions.org/questions/programming-9/opening-a-file-by-using-a-named-pipe-705205/)

akm3 02-16-2009 08:16 PM

Opening a File by using a named pipe
 
Hi,

I am trying to use a function from ffmpeg library(A linux based decoder-encoder)

This function has an input like "const char *filename"

I am trying to call it with a buffer(unsigned char *buff)
So, I created a pipe, and wrote my buffer to it:

Code:

int my_pipe[2];
if(pipe(my_pipe) == -1)
{    perror("pipe call error");
        return -1;
}

write(my_pipe[1],buff,buff_size);

now, is there a way that instead of "filename", I pass my pipe to this function to read from?

(An equivalent question can be, how to call `fopen` using a file descriptor?)

SciYro 02-17-2009 05:04 AM

I dont know if this is portable to other OSs, but it works in Linux.

Each process has its own directory, placed in /proc and named after its process ID (thus all the directories with numbers). Each process-dir has a directory named 'fd', which contains a list of all active file descriptors. /proc/self is a shortcut to the current process-dir (so it wont work to pass such a name between multiple processes, you would have to construct the actual name with the process ID).

Simple make a filename using the above and the file descriptor, example:

Code:

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

int main (argc, argv)
  int argc;
  char** argv;
{
    char* buf;
    buf = "apple\n";

    int my_pipe[2];
    if(pipe(my_pipe) == -1)
      {
        perror("pipe call error");
        return -1;
      }

    write(my_pipe[1], buf, strlen(buf));

    FILE* file;
    char* filename;
    asprintf (&filename, "/proc/self/fd/%i", my_pipe[1]);
    file = fopen (filename, "r");
    if (file == NULL)
      {
        perror ("unable to open file");
        return -1;
      }
    free (filename);

    char* readbuf;
    int readsize;
    readbuf = NULL;
    readsize = 0;

    getline (&readbuf, &readsize, file);
    printf ("%s", readbuf);
    free (readbuf);

    fclose (file);
    close (my_pipe[0]);

    return 0;
}



All times are GMT -5. The time now is 11:01 AM.