//  Copyright (c) 2007, Monju System Architects
//
//  Released under the Monju-Public copyright license:
//
//  Permission is hereby granted, free of charge, to any person or entity
//  obtaining a copy of this software and associated documentation files
//  (the "Software"), to deal in the Software without restriction,
//  including without limitation the rights to use, copy, modify, merge,
//  publish, distribute, sublicense, and/or sell copies and modifications
//  of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of published, sold, or
//  ownership-transferred versions of the Software. This notice is not
//  required for binary-only releases or binary-only derivatives of the
//  Software, or documentation provided with binary-only releases and
//  binary-only derivatives.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.




//  INCLUDES.
#ifdef _WIN32
	#include <Windows.h>
#else
	#include <stdlib.h>
#endif



//  DEFINITIONS.
#ifdef _WIN32
	#define PROCESS_INFO    PROCESS_INFORMATION
#else
	#define PROCESS_INFO    int
#endif



//  isSubprocessDone()
//
//  Non-blocking call to determine if a subprocess has completed.  If the subprocess
//  terminates without an exit status (with a signal) and <pStatus> is not NULL, the 
//  status is set to -1.  Returns true if the subprocess has finished and false
//  otherwise.
bool isSubprocessDone(const PROCESS_INFO& processInfo, int* pStatus=NULL) {
    #ifdef _WIN32
	    DWORD exitCode;
	    if(0 ==  GetExitCodeProcess(processInfo.hProcess, &exitCode)) {
	        return false;
	    }
	    if (pStatus != NULL) {
			*pStatus = exitCode;
		}
		return true;
	#else
	    int status;
	    int result = waitpid(processInfo, &status, WNOHANG);
	    if (result < 0) {
	        throw("waidpid error.");
	    }
	    if (result == 0) {
	        return false;
	    }
	    if (!WIFEXITED(status)) {
			if (pStatus != NULL) {
			    *pStatus = -1;
			} 
		    return true;
	    }
		if (pStatus != NULL) {
		    *pStatus = WEXITSTATUS(*pStatus);
		}
		return true;
	#endif
}




