c++ - CreateProcess() 启动子应用程序

标签 c++ c visual-c++

我想使用 CreateProcess 函数从主应用程序启动子应用程序,步骤如下:

  1. 从主程序启动了一个子.exe程序,但没有子程序的窗口
  2. 等待rand Sleep
  3. 然后先终止子应用程序,然后终止主应用程序。

在下面的示例代码中,但是子程序与窗口(在本例中为记事本)一起运行,并且我无法终止子程序。

#include "stdafx.h"
#include <windows.h>
#include <conio.h>
#include <strsafe.h>
#include <direct.h>
#include <string.h>

int main(int argc, char* argv[])
{   

HWND                hWnd;
STARTUPINFO         sInfo;
PROCESS_INFORMATION pInfo;

ZeroMemory(&sInfo, sizeof(sInfo));
sInfo.cb = sizeof(sInfo);
ZeroMemory(&pInfo, sizeof(pInfo));

if (CreateProcess("C:\\WINDOWS\\System32\\notepad.exe", NULL, NULL, NULL, false, CREATE_NO_WINDOW, NULL, NULL, &sInfo, &pInfo))
{
    printf("Sleeping 100ms...\n");
    Sleep(100);

    DWORD dwExitCode;
    GetExitCodeProcess(pInfo.hProcess, &dwExitCode);

    CloseHandle(pInfo.hThread);
    CloseHandle(pInfo.hProcess);

    }

system("pause");

return 0;

 }

最佳答案

记事本窗口显示的原因是它不是控制台应用程序。 MSDN 关于 CREATE_NO_WINDOW 是这么说的:

The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set. This flag is ignored if the application is not a console application, or if it is used with either CREATE_NEW_CONSOLE or DETACHED_PROCESS.

相反,请使用您传入的STARTUPINFO:

sInfo.dwFlags = STARTF_USESHOWWINDOW;
sInfo.wShowWindow = SW_HIDE;

我相信这会影响记事本主函数中 WinMain 的最后一个参数,但我不确定。

至于为什么记事本没有关闭,GetExitCodeProcess实际上并没有结束进程,它只是检索状态。您可以使用 TerminateProcess 代替:

TerminateProcess(pInfo.hProcess, 0);

关于c++ - CreateProcess() 启动子应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14302127/

相关文章:

c++ - MS ADO DLL 没有正确安装?

c++ - RAII 应该导致内存泄漏吗?

node.js - 在 Visual Studio 2015 中构建 node-gyp 项目时出现 LNK1104 错误

c - in_addr 随机结果

c - 如何从函数返回字符数组?然后在另一个函数中使用返回的字符?

c++ - 如何在C++中输入128位无符号整数

c++ - C++程序返回 “abort() has been called”,没有其他错误?

c++ - 使用 gcc 8.2.1 时出现 strncat Wformat 溢出警告

c++ - C++中的二叉搜索树复制构造函数

c - 桌面应用程序需要服务器端调试