#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

void redirect ( int *me )
{
    int newfd;
    char filename[256];
    char hostname[256];

/* redirect standard out*/
    sprintf(filename,"stdout.%05d",*me);
    if ((newfd = open( filename, O_CREAT | O_WRONLY | O_TRUNC, 0666 )) < 0 )
    {
        perror("error_dup: cannot open stdout.nnnn");
        fprintf(stderr,"...sending output to standard output and continuing.\n");
        return;
    }
    if( dup2( newfd, STDOUT_FILENO ) < 0 )
    {
        perror("error_dup: dup2 fails to change output descriptor");
        fprintf(stderr,"...sending output to standard output and continuing.\n");
        close(newfd);
        return;
    }

/* redirect standard error */
    sprintf(filename,"stderr.%05d",*me);
    if ((newfd = open( filename, O_CREAT | O_WRONLY | O_TRUNC, 0666 )) < 0 )
    {
        perror("error_dup: cannot open stderr.nnnn");
        fprintf(stderr,"...sending error to standard error and continuing.\n");
        return;
    }
    if( dup2( newfd, STDERR_FILENO ) < 0 )
    {
        perror("error_dup: dup2 fails to change error descriptor");
        fprintf(stderr,"...sending error to standard error and continuing.\n");
        close(newfd);
        return;
    }

    gethostname( hostname, 256 );

    fprintf( stdout, "mype: %d hostname: %s\n", *me, hostname );
    fprintf( stderr, "mype: %d hostname: %s\n", *me, hostname );
}

void redirect_ ( int *me ) { redirect ( me ); }
void redirect__ ( int *me ) { redirect ( me ); }
