#include "stdafx.h"
#include <windows.h>
//进程间通信
//管道
typedef struct tagParam
{
HANDLE hWritePipe;
HANDLE hReadPipe;
}PARAM, *LPPARAM;
int ThreadFunc(LPVOID param)
{
char szBuf[4096];
DWORD dwReadBytes = 0;
char strShellPath[MAX_PATH] = { 0 };
DWORD dwBytesRead;
DWORD dwTotalBytesAvail;
BOOL bRet = FALSE;
LPVOID lpBuffer = NULL;
HANDLE hReadPipe = ((LPPARAM)param)->hReadPipe;
HANDLE hWritePipe = ((LPPARAM)param)->hWritePipe;
while (TRUE)
{
bRet = PeekNamedPipe(hReadPipe, szBuf, sizeof(4096), &dwBytesRead, &dwTotalBytesAvail, NULL);
if (bRet)
{
if (dwBytesRead <= 0)
{
continue;
}
memset(szBuf, 0, sizeof(szBuf));
lpBuffer = (LPBYTE)LocalAlloc(LPTR, dwTotalBytesAvail + 1);
if (lpBuffer == NULL)
{
break;
}
memset(lpBuffer, 0, dwTotalBytesAvail + 1);
ReadFile(hReadPipe, lpBuffer, dwTotalBytesAvail, &dwBytesRead, NULL);
if (!bRet)
{
if (lpBuffer != NULL)
{
LocalFree(lpBuffer);
lpBuffer = NULL;
}
break;
}
printf("%s", lpBuffer);
}
}
return 0;
}
int main(int argc, char* argv[])
{
HANDLE hCmdReadPipe = NULL;
HANDLE hReadPipe = NULL;
HANDLE hCmdWritePipe = NULL;
HANDLE hWritePipe = NULL;
BOOL fRet = FALSE;
char szBuf[4096];
BOOL bRet = FALSE;
LPVOID lpBuffer = NULL;
PARAM param;
DWORD dwWriteBytes;
SECURITY_ATTRIBUTES sa = { 0 };
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
fRet = CreatePipe(&hCmdReadPipe, &hWritePipe, &sa, 0);
if(!fRet)
{
return GetLastError();
}
fRet = CreatePipe(&hReadPipe, &hCmdWritePipe, &sa, 0);
if (!fRet)
{
return GetLastError();
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(STARTUPINFO));
memset(&pi, 0, sizeof(PROCESS_INFORMATION));
si.cb = sizeof(STARTUPINFO);
si.hStdInput = hCmdReadPipe;
si.hStdOutput = hCmdWritePipe;
si.hStdError = hCmdWritePipe;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
fRet = CreateProcess(NULL, "cmd", NULL, NULL, TRUE,
NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
if (!fRet)
{
return GetLastError();
}
param.hReadPipe = hReadPipe;
param.hWritePipe = hWritePipe;
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ThreadFunc, ¶m, 0,NULL);
while (TRUE)
{
memset(szBuf, 0, sizeof(szBuf));
gets(szBuf);
strcat(szBuf, "\r\n");
WriteFile(hWritePipe, szBuf, strlen(szBuf), &dwWriteBytes, NULL);
}
return 0;
}
就是创建两条无名管道,然后本控制台程序与新建的cmd程序进行通讯即可。
这个程序的问题是没有做结束cmd进程的等待事件,然后就是显示的话命令会显示两次,可以考虑设置程序光标的位置来去掉,这里我就不写了,没什么技术含量