utilsexc.cpp
来自「A*算法 A*算法 A*算法 A*算法A*算法A*算法」· C++ 代码 · 共 960 行 · 第 1/2 页
CPP
960 行
/////////////////////////////////////////////////////////////////////////////
// Name: src/msw/utilsexc.cpp
// Purpose: wxExecute implementation for MSW
// Author: Julian Smart
// Modified by:
// Created: 04/01/98
// RCS-ID: $Id: utilsexc.cpp,v 1.80.2.3 2005/11/24 20:34:42 ABX Exp $
// Copyright: (c) 1998-2002 wxWidgets dev team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/utils.h"
#include "wx/app.h"
#include "wx/intl.h"
#include "wx/log.h"
#endif
#include "wx/stream.h"
#include "wx/process.h"
#include "wx/apptrait.h"
#include "wx/module.h"
#include "wx/msw/private.h"
#include <ctype.h>
#if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
#include <direct.h>
#ifndef __MWERKS__
#include <dos.h>
#endif
#endif
#if defined(__GNUWIN32__)
#include <sys/unistd.h>
#include <sys/stat.h>
#endif
#if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
#ifndef __UNIX__
#include <io.h>
#endif
#ifndef __GNUWIN32__
#include <shellapi.h>
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef __WATCOMC__
#if !(defined(_MSC_VER) && (_MSC_VER > 800))
#include <errno.h>
#endif
#endif
#include <stdarg.h>
#if wxUSE_IPC
#include "wx/dde.h" // for WX_DDE hack in wxExecute
#endif // wxUSE_IPC
// implemented in utils.cpp
extern "C" WXDLLIMPEXP_BASE HWND
wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// this message is sent when the process we're waiting for terminates
#define wxWM_PROC_TERMINATED (WM_USER + 10000)
// ----------------------------------------------------------------------------
// this module globals
// ----------------------------------------------------------------------------
// we need to create a hidden window to receive the process termination
// notifications and for this we need a (Win) class name for it which we will
// register the first time it's needed
static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class");
static const wxChar *gs_classForHiddenWindow = NULL;
// ----------------------------------------------------------------------------
// private types
// ----------------------------------------------------------------------------
// structure describing the process we're being waiting for
struct wxExecuteData
{
public:
~wxExecuteData()
{
if ( !::CloseHandle(hProcess) )
{
wxLogLastError(wxT("CloseHandle(hProcess)"));
}
}
HWND hWnd; // window to send wxWM_PROC_TERMINATED to
HANDLE hProcess; // handle of the process
DWORD dwProcessId; // pid of the process
wxProcess *handler;
DWORD dwExitCode; // the exit code of the process
bool state; // set to false when the process finishes
};
class wxExecuteModule : public wxModule
{
public:
virtual bool OnInit() { return true; }
virtual void OnExit()
{
if ( *gs_classForHiddenWindow )
{
if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
{
wxLogLastError(_T("UnregisterClass(wxExecClass)"));
}
gs_classForHiddenWindow = NULL;
}
}
private:
DECLARE_DYNAMIC_CLASS(wxExecuteModule)
};
#if wxUSE_STREAMS && !defined(__WXWINCE__)
// ----------------------------------------------------------------------------
// wxPipeStreams
// ----------------------------------------------------------------------------
class wxPipeInputStream: public wxInputStream
{
public:
wxPipeInputStream(HANDLE hInput);
virtual ~wxPipeInputStream();
// returns true if the pipe is still opened
bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
// returns true if there is any data to be read from the pipe
virtual bool CanRead() const;
protected:
size_t OnSysRead(void *buffer, size_t len);
protected:
HANDLE m_hInput;
DECLARE_NO_COPY_CLASS(wxPipeInputStream)
};
class wxPipeOutputStream: public wxOutputStream
{
public:
wxPipeOutputStream(HANDLE hOutput);
virtual ~wxPipeOutputStream() { Close(); }
bool Close();
protected:
size_t OnSysWrite(const void *buffer, size_t len);
protected:
HANDLE m_hOutput;
DECLARE_NO_COPY_CLASS(wxPipeOutputStream)
};
// define this to let wxexec.cpp know that we know what we're doing
#define _WX_USED_BY_WXEXECUTE_
#include "../common/execcmn.cpp"
// ----------------------------------------------------------------------------
// wxPipe represents a Win32 anonymous pipe
// ----------------------------------------------------------------------------
class wxPipe
{
public:
// the symbolic names for the pipe ends
enum Direction
{
Read,
Write
};
// default ctor doesn't do anything
wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
// create the pipe, return true if ok, false on error
bool Create()
{
// default secutiry attributes
SECURITY_ATTRIBUTES security;
security.nLength = sizeof(security);
security.lpSecurityDescriptor = NULL;
security.bInheritHandle = TRUE; // to pass it to the child
if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
{
wxLogSysError(_("Failed to create an anonymous pipe"));
return false;
}
return true;
}
// return true if we were created successfully
bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
// return the descriptor for one of the pipe ends
HANDLE operator[](Direction which) const { return m_handles[which]; }
// detach a descriptor, meaning that the pipe dtor won't close it, and
// return it
HANDLE Detach(Direction which)
{
HANDLE handle = m_handles[which];
m_handles[which] = INVALID_HANDLE_VALUE;
return handle;
}
// close the pipe descriptors
void Close()
{
for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
{
if ( m_handles[n] != INVALID_HANDLE_VALUE )
{
::CloseHandle(m_handles[n]);
m_handles[n] = INVALID_HANDLE_VALUE;
}
}
}
// dtor closes the pipe descriptors
~wxPipe() { Close(); }
private:
HANDLE m_handles[2];
};
#endif // wxUSE_STREAMS
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// process termination detecting support
// ----------------------------------------------------------------------------
// thread function for the thread monitoring the process termination
static DWORD __stdcall wxExecuteThread(void *arg)
{
wxExecuteData * const data = (wxExecuteData *)arg;
if ( ::WaitForSingleObject(data->hProcess, INFINITE) != WAIT_OBJECT_0 )
{
wxLogDebug(_T("Waiting for the process termination failed!"));
}
// get the exit code
if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
{
wxLogLastError(wxT("GetExitCodeProcess"));
}
wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
wxT("process should have terminated") );
// send a message indicating process termination to the window
::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
return 0;
}
// window procedure of a hidden window which is created just to receive
// the notification message when a process exits
LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
if ( message == wxWM_PROC_TERMINATED )
{
DestroyWindow(hWnd); // we don't need it any more
wxExecuteData * const data = (wxExecuteData *)lParam;
if ( data->handler )
{
data->handler->OnTerminate((int)data->dwProcessId,
(int)data->dwExitCode);
}
if ( data->state )
{
// we're executing synchronously, tell the waiting thread
// that the process finished
data->state = 0;
}
else
{
// asynchronous execution - we should do the clean up
delete data;
}
return 0;
}
else
{
return ::DefWindowProc(hWnd, message, wParam, lParam);
}
}
// ============================================================================
// implementation of IO redirection support classes
// ============================================================================
#if wxUSE_STREAMS && !defined(__WXWINCE__)
// ----------------------------------------------------------------------------
// wxPipeInputStreams
// ----------------------------------------------------------------------------
wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
{
m_hInput = hInput;
}
wxPipeInputStream::~wxPipeInputStream()
{
if ( m_hInput != INVALID_HANDLE_VALUE )
::CloseHandle(m_hInput);
}
bool wxPipeInputStream::CanRead() const
{
if ( !IsOpened() )
return false;
DWORD nAvailable;
// function name is misleading, it works with anon pipes as well
DWORD rc = ::PeekNamedPipe
(
m_hInput, // handle
NULL, 0, // ptr to buffer and its size
NULL, // [out] bytes read
&nAvailable, // [out] bytes available
NULL // [out] bytes left
);
if ( !rc )
{
if ( ::GetLastError() != ERROR_BROKEN_PIPE )
{
// unexpected error
wxLogLastError(_T("PeekNamedPipe"));
}
// don't try to continue reading from a pipe if an error occurred or if
// it had been closed
::CloseHandle(m_hInput);
wxPipeInputStream *self = wxConstCast(this, wxPipeInputStream);
self->m_hInput = INVALID_HANDLE_VALUE;
self->m_lasterror = wxSTREAM_EOF;
nAvailable = 0;
}
return nAvailable != 0;
}
size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
{
if ( !IsOpened() )
{
m_lasterror = wxSTREAM_EOF;
return 0;
}
DWORD bytesRead;
if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
{
m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
? wxSTREAM_EOF
: wxSTREAM_READ_ERROR;
}
// bytesRead is set to 0, as desired, if an error occurred
return bytesRead;
}
// ----------------------------------------------------------------------------
// wxPipeOutputStream
// ----------------------------------------------------------------------------
wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
{
m_hOutput = hOutput;
// unblock the pipe to prevent deadlocks when we're writing to the pipe
// from which the child process can't read because it is writing in its own
// end of it
DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
if ( !::SetNamedPipeHandleState
(
m_hOutput,
&mode,
NULL, // collection count (we don't set it)
NULL // timeout (we don't set it neither)
) )
{
wxLogLastError(_T("SetNamedPipeHandleState(PIPE_NOWAIT)"));
}
}
bool wxPipeOutputStream::Close()
{
return ::CloseHandle(m_hOutput) != 0;
}
size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
{
m_lasterror = wxSTREAM_NO_ERROR;
DWORD totalWritten = 0;
while ( len > 0 )
{
DWORD chunkWritten;
if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) )
{
m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
? wxSTREAM_EOF
: wxSTREAM_WRITE_ERROR;
break;
}
if ( !chunkWritten )
break;
buffer = (char *)buffer + chunkWritten;
totalWritten += chunkWritten;
len -= chunkWritten;
}
return totalWritten;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?