转载自:http://blog.csdn.net/morewindows/article/details/8683830
本篇介绍一个简单而又实用的进程通信方式——父进程向子进程传入参数并获取子进程返回值。这个非常简单:
1.父进程向子进程传入参数可以由CreateProcess()函数来完成,注意子进程是通过GetCommandLine()来获取这个参数而且不是char *argv[]。
2.父进程要获取子进程的返回值可以在等待子进程结束后通过GetExitCodeProcess并传入子进程句柄来获取子进程中main或WinMain函数的返回值。
下面就结出实例代码,首先来看子进程的程序代码:
- //进程通信之三 父进程传参数与子进程返回值
- //http://blog.csdn.net/morewindows/article/details/8683830
- //By MoreWindows( http://blog.csdn.net/MoreWindows )
- #include <windows.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- int main(int argc, char *argv[])
- {
- // 通过GetCommandLine()获取父进程通过CreateProcess传给子进程的参数
- // 注意这与argv[]不同如strlen(argv[1])会出错
- srand((unsigned int)time(NULL));
- return strlen(GetCommandLine()) + rand() % 10;
- }
然后是父进程的程序代码,代码中的AdjustProcessCurrentDirectory();函数可以参考《Windows VC++ 调整进程当前目录为程序可执行文件所在目录》(http://blog.csdn.net/morewindows/article/details/8683519):
- //进程通信之三 父进程传参数与子进程返回值
- //http://blog.csdn.net/morewindows/article/details/8683830
- //By MoreWindows( http://blog.csdn.net/MoreWindows )
- #include <windows.h>
- #include <stdio.h>
- #include <string.h>
- #include <conio.h>
- // 启动子进程并传入参数,等待子进程结束后获取其返回值。
- BOOL GetChildProcessExitCode(const char *pstrChildProcessExeFileName,
- char *pstrConmandLine,
- DWORD *pdwExitCode, BOOL fHide = TRUE)
- {
- //子进程启动信息设置
- STARTUPINFO si;
- si.cb = sizeof(STARTUPINFO);
- GetStartupInfo(&si);
- si.wShowWindow = fHide ? SW_HIDE : SW_SHOW;
- si.dwFlags = STARTF_USESHOWWINDOW;
- // 运行子进程并等待其结束
- PROCESS_INFORMATION pi;
- CreateProcess(pstrChildProcessExeFileName, pstrConmandLine, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi);
- WaitForSingleObject(pi.hProcess, INFINITE);
- // 获取子进程返回值
- BOOL flag = GetExitCodeProcess(pi.hProcess, pdwExitCode);
- CloseHandle(pi.hProcess);
- CloseHandle(pi.hThread);
- return flag;
- }
- int main()
- {
- printf(" 进程通信之三 父进程传参数与子进程返回值 ");
- printf(" - http://blog.csdn.net/morewindows/article/details/8683830 - ");
- printf(" -- By MoreWindows( http://blog.csdn.net/MoreWindows ) -- ");
- AdjustProcessCurrentDirectory();
- const char *pstrChildProcessExeFileName = "ChildProcess.exe";
- const int RUN_CHILDPROCESS_NUMBER = 5;
- char szCommandLine[30] = "MoreWindows";
- int nCommandLineLen = strlen(szCommandLine);
- for (int i = 0; i < RUN_CHILDPROCESS_NUMBER; i++)
- {
- // 运行子进程并获取返回值
- DWORD dwExitCode;
- if (GetChildProcessExitCode(pstrChildProcessExeFileName, szCommandLine, &dwExitCode, TRUE))
- printf("子进程返回值为 %d ", dwExitCode - nCommandLineLen);
- else
- printf("GetExitCodeProcess()失败 %d ", GetLastError());
- Sleep(1000);
- }
- getch();
- return 0;
- }
程序运行结果如下: