[Fwd: Re: dangerous stuff popen2()]

Martijn van Oosterhout kleptog at svana.org
Mon Oct 15 22:12:57 EST 2001


On Mon, Oct 15, 2001 at 09:24:05AM +0000, Paul Matthews wrote:
> Patrick Cole's been helping me out, but I still can't quite get it to
> work. Anyone got any good ideas.

You're suffering from excess file description syndrome. You create four file
descriptors with those pipe commands. After you fork you have essentially
two pipes with two inputs and two outputs each.

>   if( pid == 0 )
>   {
>     xdup2( input[0], STDIN_FILENO );
>     xdup2( output[1], STDOUT_FILENO );
>     char *argv[4];

      close( input[0] ); // Close excess file descriptors
      close( input[1] ); // If you don't do this, sort will never get an EOF
      close( output[0] );
      close( output[1] );

>     argv[0] = "sort";
>     argv[1] = "-t";
>     argv[2] = "\"\t\"";
>     argv[3] = NULL;
>     execvp( "sort", argv );
>     perror("execvp");
>     _exit(1);
>   }
> 
>   FILE * sortin  = xfopen( input[1], "w" );
>   FILE * sortout = xfopen( output[0], "r" ); 
>   
>   xfputs( "beta\n", sortin );
>   xfputs( "alpha\n", sortin );
>   xfputs( "gamma\n", sortin );
>   xfputs( "delta\n", sortin );
>   fclose( sortin );
>   close( input[1] );
>   close( input[0] );

    close( output[1] );  // If you don't do this, we'll never receive an EOF from sort

>   fprintf( stderr, "OK so far\n" );
>   
>   char buffer[30];
>   while( fgets(buffer,30,sortout) )
>   {
>     fprintf( stdout, "%s\n", buffer );
>     fflush( stdout );
>   }
> }
> 

You need to close *all* the input descriptors, before *any* of the output
descriptors return an EOF.
-- 
Martijn van Oosterhout <kleptog at svana.org>
http://svana.org/kleptog/
> Magnetism, electricity and motion are like a three-for-two special offer:
> if you have two of them, the third one comes free.




More information about the linux mailing list