a.exe通过preocess调用b.exe , b.exe运行结束如何返回一个string类型的结果
时间: 2023-11-22 10:56:36 浏览: 59
计算string类型算式的结果
4星 · 用户满意度95%
在b.exe运行结束时,可以通过将结果写入共享内存或文件的方式来实现返回string类型的结果。具体步骤如下:
1. 在a.exe中创建一个共享内存或文件,用于存储b.exe返回的结果。
2. 在a.exe中启动b.exe进程,并将共享内存地址或文件路径作为参数传递给b.exe。
3. 在b.exe中将结果写入共享内存或文件中。
4. 在a.exe中读取共享内存中的结果或读取文件中的结果,并将其转换为string类型。
下面是一个示例代码:
在a.exe中:
```c++
#include <windows.h>
#include <iostream>
int main()
{
HANDLE hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
sizeof(char[256]), // maximum object size (low-order DWORD)
"Local\\MyFileMappingObject"); // name of the mapping object
if (hMapFile == NULL)
{
std::cout << "Could not create file mapping object: " << GetLastError() << std::endl;
return 1;
}
char* pBuffer = (char*)MapViewOfFile(
hMapFile, // handle to mapping object
FILE_MAP_ALL_ACCESS, // read/write permission
0, // high-order DWORD of offset
0, // low-order DWORD of offset
256); // number of bytes to map
if (pBuffer == NULL)
{
std::cout << "Could not map view of file: " << GetLastError() << std::endl;
CloseHandle(hMapFile);
return 1;
}
STARTUPINFO si = { 0 };
si.cb = sizeof(si);
PROCESS_INFORMATION pi = { 0 };
TCHAR szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, MAX_PATH);
if (!CreateProcess(szPath, (LPSTR)"b.exe Local\\MyFileMappingObject", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
std::cout << "CreateProcess failed: " << GetLastError() << std::endl;
UnmapViewOfFile(pBuffer);
CloseHandle(hMapFile);
return 1;
}
WaitForSingleObject(pi.hProcess, INFINITE);
std::cout << "Result from b.exe: " << pBuffer << std::endl;
UnmapViewOfFile(pBuffer);
CloseHandle(hMapFile);
return 0;
}
```
在b.exe中:
```c++
#include <windows.h>
#include <iostream>
int main(int argc, char* argv[])
{
HANDLE hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
argv[1]); // name of the mapping object
if (hMapFile == NULL)
{
std::cout << "Could not open file mapping object: " << GetLastError() << std::endl;
return 1;
}
char* pBuffer = (char*)MapViewOfFile(
hMapFile, // handle to mapping object
FILE_MAP_WRITE, // write permission
0, // high-order DWORD of offset
0, // low-order DWORD of offset
256); // number of bytes to map
if (pBuffer == NULL)
{
std::cout << "Could not map view of file: " << GetLastError() << std::endl;
CloseHandle(hMapFile);
return 1;
}
strcpy_s(pBuffer, 256, "Hello, World!");
UnmapViewOfFile(pBuffer);
CloseHandle(hMapFile);
return 0;
}
```
阅读全文