/* processhandler.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2010-2011 Ralf Hoffmann.
 * You can contact me at: ralf@boomerangsworld.de
 *   or http://www.boomerangsworld.de/worker
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "processhandler.hh"

void ProcessHandler::addChildProcess( int pid, RefCount< GenericCallbackArg<void, int> > pea )
{
    m_child_actions.push_back( list_entry_t( pid, pea ) );
}

void ProcessHandler::checkChildren( int pid )
{
    std::list< list_entry_t >::iterator it1;

    if ( pid == 0 ) return;

    for ( it1 = m_child_actions.begin();
          it1 != m_child_actions.end(); ) {
        std::list< list_entry_t >::iterator next_it = it1;

        next_it++;

        if ( pid < 0 || it1->first == pid ) {
            int status = 0, ret;

            ret = waitpid( it1->first, &status, WNOHANG );
            if ( ret == it1->first ) {
                // process finished
#ifdef DEBUG
                printf( "Process %d finished (status %d)\n", ret, WEXITSTATUS( status ) );
#endif

                if ( it1->second.get() != NULL ) {
                    it1->second->callback( WEXITSTATUS( status ) );
                }

                m_child_actions.erase( it1 );
    
                if ( pid > 0 ) break;
            }
        }

        it1 = next_it;
    }
}

bool ProcessHandler::empty() const
{
    return m_child_actions.empty();
}

void ProcessHandler::clearProcesses()
{
    m_child_actions.clear();
}
