我希望我的 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;
}
这是我之前在寻找答案时发现的解决方案。
它指出您应该始终避免使用 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)