关于控制台程序的命令写入,请指教。
我想在一个对话框程序中,按下某按钮后执行“cmd”,然后写入“dir\r\n”命令,程序报告写入了5个字节,但是cmd窗口没反应。
大侠能否看看我的这段代码有什么毛病,谢谢。
void CCmdPipeDlg::OnButtonDo()
{
// TODO: Add your control notification handler code here
//创建单个进程,通过管道写入命令
SECURITY_ATTRIBUTES sat = {0};
sat.nLength = sizeof( SECURITY_ATTRIBUTES );
sat.lpSecurityDescriptor = NULL;
sat.bInheritHandle = TRUE;
HANDLE hPipeRead1=NULL, hPipeWrite1=NULL;
HANDLE hPipeRead2=NULL, hPipeWrite2=NULL;
BOOL bPipeOk1 = CreatePipe( &hPipeRead1, &hPipeWrite1, &sat, NULL );
BOOL bPipeOk2 = CreatePipe( &hPipeRead2, &hPipeWrite2, &sat, NULL );
if( !bPipeOk1 || !bPipeOk2 )
{
return;
}
STARTUPINFO StartUpInfo = {0};
PROCESS_INFORMATION ProInfo = {0};
StartUpInfo.cb = sizeof( StartUpInfo );
StartUpInfo.lpReserved = NULL;
StartUpInfo.dwFlags = 0;
StartUpInfo.cbReserved2 = 0;
StartUpInfo.lpReserved2 = NULL;
StartUpInfo.lpDesktop = NULL;
StartUpInfo.lpTitle = NULL;
StartUpInfo.dwX = 0;
StartUpInfo.dwY = 0;
StartUpInfo.dwXSize = 0;
StartUpInfo.dwYSize = 0;
StartUpInfo.dwXCountChars = 0;
StartUpInfo.dwYCountChars = 0;
StartUpInfo.dwFillAttribute = 0;
StartUpInfo.dwFlags = NULL;
StartUpInfo.wShowWindow = SW_SHOW;
StartUpInfo.hStdInput = hPipeRead1;
StartUpInfo.hStdOutput = hPipeWrite2;//NULL;
StartUpInfo.hStdError = hPipeWrite2;//NULL;
BOOL bProOk = CreateProcess( NULL, "cmd",
NULL, NULL, TRUE, NULL, NULL, NULL,
&StartUpInfo, &ProInfo );
if( !bProOk )
{
return;
}
CloseHandle( hPipeRead1 );
CloseHandle( hPipeWrite2 );
char szCmdLine[1024] = "dir\r\n";
// 写入命令
ULONG uWrited = 0;
BOOL bWriteOk = WriteFile( hPipeWrite1, szCmdLine, strlen(szCmdLine), &uWrited, NULL );
char szWrited[256] = {0};
sprintf( szWrited, "writed: %d", uWrited );
MessageBox( szWrited );
// 关闭进程
CloseHandle( hPipeRead2 );
CloseHandle( hPipeWrite1 );
CloseHandle( ProInfo.hProcess);
return;
}