zoukankan      html  css  js  c++  java
  • Windows下匿名管道进程通信

    ##昨天做网易雷火的一道笔试题,有一个密码锁是由一个函数实现的,函数Y=f(X);现获得了该函数的一个可执行文件,希望编写代码来测试它##

    下载来的可执行文件是一个控制台程序,输入一个浮点数X,会获得相应的Y;

    现在希望实现它:

    我们假设该可执行文件的源代码(子进程的实现机制)为:

    int main(int argc, char* argv[])
    {
    	double n;
    	while (cin >> n)
    	{
    		cout << 2 * n <<endl;
    	}
    	
    	return 0;
    }

    实际上我们并不知道f函数的具体实现机制,这里只是模拟。我们将该程序编译链接成:ConsoleApplication1.exe,放于E盘下。

    我们需要在主程序里实现进程的通信来完成测试:

    //匿名管道进程通信
    # include <iostream>
    # include <Windows.h>
    
    
    
    int main(int argc, char * argv[])
    {
    	SECURITY_ATTRIBUTES sa;
    	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    	sa.lpSecurityDescriptor = NULL;
    	sa.bInheritHandle = TRUE;
    
    	HANDLE hParentRead, hChildWrite;
    	if (!CreatePipe(&hParentRead, &hChildWrite, &sa, 0)) {
    		std::cout<< "Error On CreatePipe()"<<std::endl;
    		return 0;
    	}
    
    	HANDLE hChildRead, hParentWrite;
    	if (!CreatePipe(&hChildRead, &hParentWrite, &sa, 0)) {
    		std::cout << "Error On CreatePipe()" << std::endl;
    		return 0;
    	}
    
    	STARTUPINFO si;
    	si.cb = sizeof(STARTUPINFO);
    	GetStartupInfo(&si);
    	si.hStdError = hChildWrite;
    	si.hStdOutput = hChildWrite;
    	si.hStdInput = hChildRead;
    	//si.wShowWindow = SW_HIDE;
    	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    
    	PROCESS_INFORMATION pi;
    
    	TCHAR * appPath = TEXT("E:\ConsoleApplication1.exe");
    	if (!CreateProcess(appPath, NULL, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) {
    		std::cout << "Error on CreateProcess()" << std::endl;
    		return 0;
    	}
    
    	CloseHandle(hChildWrite);
    	CloseHandle(hChildRead);
    
    	double inputdouble;
    	std::cin >> inputdouble;
    
    	char buffer[4096];
    	sprintf(buffer, "%f", inputdouble);
    
    	DWORD bytesRead;
    	if (WriteFile(hParentWrite, &buffer, 4096, &bytesRead, NULL) == NULL)
    	{
    		std::cout << "Write Failed" << std::endl;
    		return 0;
    	}
    	memset(buffer,0,4096);
    
    	if (ReadFile(hParentRead, buffer, 4095, &bytesRead, NULL) == NULL)
    	{
    		std::cout << "Read Failed" << std::endl;
    		return 0;
    	}
    	std::cout << buffer;
    
    	
    	return 0;
    }

    在主程序中创建子进程并完成进程间的通信。

  • 相关阅读:
    [LeetCode] Minimum Depth of Binary Tree 二叉树最小深度
    [LeetCode] Intersection of Two Linked Lists 两链表是否相交
    [LeetCode] Permutations II 排列
    [LeetCode] Maximum Product Subarray 连续数列最大积
    Ncut matlab 代码bug 修复
    [LeetCode] Jump Game II 贪心
    【poj2182】【poj2828】树状数组/线段树经典模型:逆序查找-空位插入法
    【hdu1828/poj1177】线段树求矩形周长并
    【hdu1255】线段树求矩形面积交
    【hdu1542】线段树求矩形面积并
  • 原文地址:https://www.cnblogs.com/oneDongHua/p/14264033.html
Copyright © 2011-2022 走看看