#pragma once
#include "timeout.h"
#include "SyncObject.h"
#include "Buffer.h"
#include "connection.h"


class CSubProcessException
{
public:
	CSubProcessException(CString info,int retry=0) {m_info = info;}

	CString	m_info;
};

class CSubProcess :
	public CTimeOut
{
public:
	CSubProcess(CServer *server,CConnectionInterrupt interrupt);
	virtual ~CSubProcess(void);
	virtual void Break();

	static CString GetCGICommand(CServer *server,CString path,CString queryDecoded);

	int RunSubProcess(CString command,CString workPath,CString threadID);

	int ProsessRunning();
	void AddEnvironment(CString env);
	void AddCGIServerEnvironment(CServer *server,CWorkspaceAccess context,CRequest request,CAlias alias);
	static void GetCGIServerEnvironment(CWorkspaceAccess env,CServer *server,CWorkspaceAccess context,CRequest request,CAlias alias);

	//	入出力バッファ
	CBuffer				m_stdin;
	CBuffer				m_stdout;
	CBuffer				m_stderr;

protected:
	virtual void OnTimeOut();
	int CreatePipe(CString threadID);
	void TerminateProcess();
	void WaitProcessTerminate();

	int ReadStdOut(CBuffer &data);
	int ReadStdErr(CBuffer &data);
	int WriteStdIn(CBuffer &data,int startIndex);
	static CString	GetFirstLine(CString path);

	CLockObject<int>		m_prosessCreated;
	CLockObject<int>		m_breakFlag;
	CBuffer					m_env;
	CServer					*m_server;
	CConnectionInterrupt	m_interrupt;

	//	セキュリティ
	SECURITY_ATTRIBUTES	m_sa;

	//	プロセス情報
	PROCESS_INFORMATION m_processInfo;

	//	StdOut
	HANDLE				m_hReadPipe;
	HANDLE				m_hWritePipe;

	//	StdIn
	HANDLE				m_hInReadPipe;
	HANDLE				m_hInWritePipe;
	HANDLE				m_hInWriteWait;
	OVERLAPPED			m_ovrlapped;


	//	StdErr
	HANDLE				m_hErrReadPipe;
	HANDLE				m_hErrWritePipe;

};
