管道的使用方法


#include<windows.h>
#include<winbase.h>
#include<iostream.h>
#include<stdio.h>

SECURITY_ATTRIBUTES stPipeA,stPipeB;
HANDLE hPipeARead,hPipeAWrite;//建立通道
HANDLE hPipeBRead,hPipeBWrite;//建立通道
STARTUPINFO stInfo;;
PROCESS_INFORMATION stProInfo;
char Cmd[MAX_PATH]="C:\\WINDOWS\\system32\\cmd.exe";//这里是我电脑cmd的路径

int main()
{
	//建立通道
	memset(&stPipeA,0,sizeof(stPipeA));
	stPipeA.bInheritHandle=TRUE;
    stPipeA.lpSecurityDescriptor=NULL;
	stPipeA.nLength=sizeof(SECURITY_ATTRIBUTES);

	if(!cr&#101;atePipe(&hPipeAWrite,&hPipeARead,&stPipeA,0))
	{
		cout<<"cr&#101;atePipe Error!"<<endl;
	}

	memset(&stPipeB,0,sizeof(stPipeB));
	stPipeB.bInheritHandle=TRUE;
	stPipeB.lpSecurityDescriptor=NULL;
	stPipeB.nLength=sizeof(SECURITY_ATTRIBUTES);

	if(!cr&#101;atePipe(&hPipeBWrite,&hPipeBRead,&stPipeB,0))
	{
        cout<<"cr&#101;atePipe Error!"<<endl;
	}
    GetStartupInfo(&stInfo);
	stInfo.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
	stInfo.hStdInput=hPipeAWrite;
	stInfo.hStdError=stInfo.hStdOutput=hPipeBRead;
	stInfo.wShowWindow=SW_HIDE;

    //创建cmd.exe进程
	if(!cr&#101;ateProcess(Cmd,NULL,NULL,NULL,TRUE,0,NULL,NULL,&stInfo,&stProInfo))
	{
		cout<<"cr&#101;ateProcess Error!"<<endl;
	}

	char bb[1024];//用来保存cmd显示的内容
	unsigned long size=0;

	//输入命令
	for(;;)
	{
		memset(bb,0,1024);
		cin>>bb;
		strcat(bb,"\r\n");//加上回车
		//执行命令
		if(!WriteFile(hPipeARead,bb,strlen(bb),&size,NULL))
		{
			cout<<"WriteFile Error!"<<endl;
		}

		//等待命令的执行
		WaitForSingleObject(stProInfo.hProcess,WAIT_TIMEOUT);

		//读去返回信息
		if(!ReadFile(hPipeBWrite,bb,1024,&size,NULL))
		{
			cout<<"ReadFile Error"<<endl;
			return 0;
		}
		//输出返回信息
		cout<<bb<<endl;
	}

	//关闭通道
	CloseHandle(hPipeARead);
	CloseHandle(hPipeAWrite);

	CloseHandle(hPipeBRead);
	CloseHandle(hPipeBWrite);

	//关闭cmd.exe
	CloseHandle(stProInfo.hProcess );
	CloseHandle(stProInfo.hThread );

	return 1;

}

随机日志

发表评论

0 评论.

Leave a Reply



[ Ctrl + Enter ]

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

CNXCT小组的博客 is Stephen Fry proof thanks to caching by WP Super Cache