/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/


#ifndef WIN32
#include	<sys/types.h>
// #include	<unistd.h>
#else
#include <stdio.h>
#endif
#include	<stdlib.h>
#include	"memory_debug.h"
#include	"utils.h"
#include	"stream.h"
#include <windows.h>
#include "init.h"

int max_fid;
extern int s_task_flag;
/*
int
launch_proc_stdio(
	STREAM ** st_in,
	STREAM ** st_out,
	STREAM ** st_err,
	char * str)
{
int p_in[2];
int p_out[2];
int p_err[2];
int id;
int fid;
int ch[2];

#ifndef WIN32
	pipe(p_in);
	pipe(p_out);
	pipe(p_err);
	id = fork1();
#endif
	if ( id == 0 ) {
		for ( fid = 0 ; fid <= max_fid ; fid ++ ) {
			if ( p_in[0] == fid )
				continue;
			if ( p_out[1] == fid )
				continue;
			if ( p_err[1] == fid )
				continue;
			close(fid);
		}
		dup(p_in[0]);
		close(p_in[0]);
		dup(p_out[1]);
		close(p_out[1]);
		dup(p_err[1]);
		close(p_err[1]);
		system(str);
		close(0);
		close(1);
		close(2);
		exit(0);
	}
	close(p_in[0]);
	close(p_out[1]);
	close(p_err[1]);
	*st_in = s_open_descripter(p_in[1],&s_pipe_table);
	*st_out = s_open_descripter(p_out[0],&s_pipe_table);
	*st_err = s_open_descripter(p_err[0],&s_pipe_table);
	return 0;
}
*/

int
launch_proc_stdio(
	STREAM ** st_in,
	STREAM ** st_out,
	STREAM ** st_err,
	char * str)
{
    STARTUPINFO  si;
    PROCESS_INFORMATION  pi;
    SECURITY_ATTRIBUTES sa;

	int IsSuccess = 0;

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    memset(&si, 0, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_USESTDHANDLES;
    si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
    si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    si.hStdError = GetStdHandle(STD_ERROR_HANDLE);

	IsSuccess = CreateProcess(NULL,str,NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
	CloseHandle(pi.hThread);

	if(IsSuccess)
    {
		if(s_task_flag & INI_WAITCHI)
			WaitForSingleObject( pi.hProcess, INFINITE );
        CloseHandle(pi.hProcess);
    }
	return 0;
}