如何从Windows中的C++程序执行另一个exe

The*_*nce 5 c++ windows

我希望我的C++程序在Windows中执行另一个.exe.我该怎么做?我正在使用Visual C++ 2010.

这是我的代码

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    unsigned int input;
    cout << "Enter 1 to execute program." << endl;
    cin >> input;
    if(input == 1) /*execute program here*/;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*tow 14

这是我之前寻找答案时找到的解决方案.
它声明你应该总是避免使用system(),因为:

  • 资源很重
  • 它会破坏安全性 - 你不知道它是一个有效的命令,或者在每个系统上做同样的事情,你甚至可以启动你不打算启动的程序.危险在于,当您直接执行程序时,它将获得与您的程序相同的权限 - 这意味着,例如,如果您以系统管理员身份运行,那么您无意中执行的恶意程序也将作为系统管理员运行.
  • 反病毒程序讨厌它,你的程序可能会被标记为病毒.

而是可以使用CreateProcess().
Createprocess()用于启动.exe并为其创建新进程.应用程序将独立于调用应用程序运行.

#include <Windows.h>

void startup(LPCSTR lpApplicationName)
{
    // additional information
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;

    // set the size of the structures
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    // start the program up
    CreateProcessA
    (
        lpApplicationName,   // the path
        argv[1],                // Command line
        NULL,                   // Process handle not inheritable
        NULL,                   // Thread handle not inheritable
        FALSE,                  // Set handle inheritance to FALSE
        CREATE_NEW_CONSOLE,     // Opens file in a separate console
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi           // Pointer to PROCESS_INFORMATION structure
    );
        // Close process and thread handles. 
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
}
Run Code Online (Sandbox Code Playgroud)

  • 有时 'argv' 变量可能超出范围。我通常只是将 argv 的值分配给另一个全局变量并使用它 (2认同)

Ste*_*ieG 10

你可以使用这个system功能

int result = system("C:\\Program Files\\Program.exe");
Run Code Online (Sandbox Code Playgroud)

  • 我们也可以向该程序传递参数吗? (2认同)

sed*_*idw 5

您可以使用 system

system("./some_command")
Run Code Online (Sandbox Code Playgroud)