/*MT*
    
    MediaTomb - http://www.mediatomb.cc/
    
    process_executor.cc - this file is part of MediaTomb.
    
    Copyright (C) 2005 Gena Batyan <bgeradz@mediatomb.cc>,
                       Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc>
    
    Copyright (C) 2006-2009 Gena Batyan <bgeradz@mediatomb.cc>,
                            Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc>,
                            Leonhard Wimmer <leo@mediatomb.cc>
    
    MediaTomb is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation.
    
    MediaTomb 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
    version 2 along with MediaTomb; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
    
    $Id: process_executor.cc 2010 2009-01-11 19:10:43Z lww $
*/

/// \file process_executor.cc

#ifdef HAVE_CONFIG_H
    #include "autoconfig.h"
#endif

#include "process_executor.h"
#include "process.h"
#include <pthread.h>
#include <signal.h>

using namespace zmm;

ProcessExecutor::ProcessExecutor(String command, Ref<Array<StringBase> > arglist)
{
#define MAX_ARGS 255
    char *argv[MAX_ARGS];
    
    argv[0] = command.c_str();
    int apos = 0;

    for (int i = 0; i < arglist->size(); i++)
    {
        argv[++apos] = arglist->get(i)->data;
        if (apos >= MAX_ARGS-1)
            break;
    }
    argv[++apos] = NULL;

    exit_status = 0;

    process_id = fork();
    
    switch (process_id)
    {
        case -1:
            throw _Exception(_("Failed to launch process ") + command);
        
        case 0:
            sigset_t mask_set;
            pthread_sigmask(SIG_SETMASK, &mask_set, NULL);
            log_debug("Launching process: %s\n", command.c_str());
            execvp(command.c_str(), argv);
        default:
            break;
    }

    log_debug("Launched process %s, pid: %d\n", command.c_str(), process_id);
}

bool ProcessExecutor::isAlive()
{
    return is_alive(process_id, &exit_status);
}
    
bool ProcessExecutor::kill()
{
    return kill_proc(process_id);
}

int ProcessExecutor::getStatus()
{
    is_alive(process_id, &exit_status);
    return exit_status;
}

ProcessExecutor::~ProcessExecutor()
{
    kill();
}

