child.c

Sapphire/src/sapphire/child.c · 2.2 KB

From the archive sapphire_0.3.zip

Download the archive   « Back to the archive contents

/*
 * Copyright (C) 1995-1997 Christopher D. Granz
 *
 * This header may not be removed.
 *
 * Refer to the file "License" included in this package for further
 * information and before using any of the following.
 */

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "sapphire.h"


/*
 * Functions
 */

/*
 * Allocates memory for a new child process structure and adds that
 * structure to the global linked-list of child process structures.
 */
CHILDP_DATA *new_child( pid_t pPid, int *pStdin, int *pStdout,
                        int *pStderr, char *pCmdLine )
{
    CHILDP_DATA *pChild = alloc_mem( sizeof( pChild ) );

    pChild->pPid        = pPid;
    pChild->iStdin[0]   = pStdin[0];
    pChild->iStdin[1]   = pStdin[1];
    pChild->iStdout[0]  = pStdout[0];
    pChild->iStdout[1]  = pStdout[1];
    pChild->iStderr[0]  = pStderr[0];
    pChild->iStderr[1]  = pStderr[1];
    pChild->pCmdLine    = str_dup( pCmdLine );
    pChild->pNext       = pChildren;
    pChildren           = pChild;

    return ( pChild );
}


bool die_child( CHILDP_DATA *pChild, int *pStatus )
{
    *pStatus                     = 0;
    waitpid( pChild->pPid, pStatus, WNOHANG );

    if ( kill( pChild->pPid, 0 ) < 0 )
    {
        /* Cleanup time! */

        if ( pChild == pChildren )
            pChildren            = pChildren->pNext;
        else
        {
            CHILDP_DATA *pPrev;

            for ( pPrev = pChildren; pPrev != NULL; pPrev = pPrev->pNext )
            {
                if ( pPrev->pNext == pChild )
                {
                    pPrev->pNext = pChild->pNext;
                    break;
                }
            }

#ifdef DEBUG
            if ( pPrev == NULL )
                wcdebug( "Child not found." );
#endif
        }

        close( pChild->iStdin[1] );
        close( pChild->iStdin[0] );
        close( pChild->iStdout[1] );
        close( pChild->iStdout[0] );
        close( pChild->iStderr[1] );
        close( pChild->iStderr[0] );
        str_free( pChild->pCmdLine );
        free_mem( (void **) &pChild );

        return ( TRUE );
    }

    return ( FALSE );
}


/*
 * End of child.c
 */

Site Stats

Snippets: 1791
Codebases: 571