[Fwd: Re: dangerous stuff popen2()]

Paul Matthews plm at pcug.org.au
Mon Oct 15 19:24:05 EST 2001


Patrick Cole's been helping me out, but I still can't quite get it to
work. Anyone got any good ideas.


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


pid_t xfork()
{
  pid_t pid = fork();
  if( pid == -1 )
  {
    perror("fork");
    exit(1);
  }
  return pid;
}


void xpipe( int filedes[2] )
{
  if( pipe(filedes) == -1 )
  {
    perror("pipe");
    exit(1);
  }
}


void xdup2( int oldfd, int newfd )
{
  if( dup2(oldfd,newfd) == -1 )
  {
    perror("dup2");
    exit(1);
  }
}


FILE * xfopen( int filedes, const char *mode )
{
  FILE * result = fdopen( filedes, mode );
  if( result == NULL )
  {
    perror( "fdopen" );
    exit(1);
  }
  return result;
}


void xfputs( const char *s, FILE *stream )
{
  if( fputs(s,stream) == EOF )
  {
    perror("fputs");
    exit(1);
  }
}


int main()
{
  int input[2], output[2];
  pid_t pid;

  xpipe(input);
  xpipe(output);

  pid = xfork();

  if( pid == 0 )
  {
    xdup2( input[0], STDIN_FILENO );
    xdup2( output[1], STDOUT_FILENO );
    char *argv[4];
    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] );
  
  fprintf( stderr, "OK so far\n" );
  
  char buffer[30];
  while( fgets(buffer,30,sortout) )
  {
    fprintf( stdout, "%s\n", buffer );
    fflush( stdout );
  }
}




More information about the linux mailing list