How to get file descriptor of buffer in memory?

后端 未结 3 615
野的像风
野的像风 2020-12-03 17:40

If I have a buffer which contains the data of a file, how can I get a file descriptor from it? This is a question derived from how to untar file in memory

3条回答
  •  失恋的感觉
    2020-12-03 17:46

    I wrote a simple example how to make filedescriptor to a memory area:

    #include 
    #include  
    #include  
    
    char buff[]="qwer\nasdf\n";
    
    int main(){
      int p[2]; pipe(p);
    
      if( !fork() ){
        for( int buffsize=strlen(buff), len=0; buffsize>len; )
          len+=write( p[1], buff+len, buffsize-len );
        return 0;
      }
    
      close(p[1]);
      FILE *f = fdopen( p[0], "r" );
      char buff[100];
      while( fgets(buff,100,f) ){
        printf("from child: '%s'\n", buff );
      }
      puts("");
    }
    

提交回复
热议问题