windows 创建匿名管道

#define CHUNK 25
#define STATICBUFFERSIZE 1000
typedef struct {
HANDLE pipe;
char buffer[STATICBUFFERSIZE];
} pipeinfo;

 

//初始化输入输出管道句柄

pipeinfo _out = { INVALID_HANDLE_VALUE,"\0"};
pipeinfo _err = { INVALID_HANDLE_VALUE,"\0"};

 

//子线程读取管道数据

DWORD WINAPI ReadFromPipe(LPVOID args)
{
pipeinfo *pi = (pipeinfo *)args;
char *lastBuf = pi->buffer;
DWORD dwRead;
BOOL ok;
char buf[2000];

again:
ok = ReadFile(pi->pipe, buf, 2000, &dwRead, 0L);
if (!ok || dwRead == 0)
{
CloseHandle(pi->pipe);
return 0;
}
else
{
buf[dwRead] = 0;
_message = QString::fromLocal8Bit(buf);
}
goto again;
return 0; /* makes the compiler happy */
}

 

//创建管道

void createPipe()
{
STARTUPINFOA si;

PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
DWORD threadID;
char msg[300];
BOOL ok;
HANDLE hProcess, h, pipeThreads[2];
char cmdline[100];

hProcess = GetCurrentProcess();
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESTDHANDLES;

si.hStdInput = INVALID_HANDLE_VALUE;

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

CreatePipe(&_out.pipe, &h, &sa, 0);


DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);

CreatePipe(&_err.pipe, &h, &sa, 0);
DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);

strcpy(cmdline, _postExEPath.toStdString().c_str());


//创建进程
ok = CreateProcessA(NULL,cmdline, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi);

CloseHandle(si.hStdOutput);
CloseHandle(si.hStdError);

WaitForInputIdle(pi.hProcess, 5000);
CloseHandle(pi.hThread);

pipeThreads[0] = CreateThread(NULL, 0, httpApiTest::ReadFromPipe, &_out, 0, &threadID);
pipeThreads[1] = CreateThread(NULL, 0, httpApiTest::ReadFromPipe, &_err, 0, &threadID);

WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
WaitForMultipleObjects(2, pipeThreads, TRUE, INFINITE);
CloseHandle(pipeThreads[0]);
CloseHandle(pipeThreads[1]);
_showTextEdit->clear();
_showTextEdit->setText(_message);
}

posted on 2017-05-19 13:00  阿兴的平凡世界  阅读(834)  评论(0编辑  收藏  举报

导航