如何在 Windows 上用 C++ 创建进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1067789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a process in C++ on Windows?
提问by Cute
Can anyone tell me how to create a process in VC++? I need to execute
谁能告诉我如何在 VC++ 中创建一个进程?我需要执行
regasm.exe testdll /tlb:test.tlb /codebase
command in that process.
命令在那个过程中。
回答by Kirill V. Lyadvinsky
regasm.exe
(Assembly Registration Tool) makes changes to the Windows Registry, so if you want to start regasm.exe
as elevated process you could use the following code:
regasm.exe
(程序集注册工具)对 Windows 注册表进行更改,因此如果您想以regasm.exe
提升的进程启动,您可以使用以下代码:
#include "stdafx.h"
#include "windows.h"
#include "shellapi.h"
int _tmain(int argc, _TCHAR* argv[])
{
SHELLEXECUTEINFO shExecInfo;
shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
shExecInfo.fMask = NULL;
shExecInfo.hwnd = NULL;
shExecInfo.lpVerb = L"runas";
shExecInfo.lpFile = L"regasm.exe";
shExecInfo.lpParameters = L"testdll /tlb:test.tlb /codebase";
shExecInfo.lpDirectory = NULL;
shExecInfo.nShow = SW_NORMAL;
shExecInfo.hInstApp = NULL;
ShellExecuteEx(&shExecInfo);
return 0;
}
shExecInfo.lpVerb = L"runas"
means that process will be started with elevated privileges. If you don't want that just set shExecInfo.lpVerb
to NULL. But under Vista or Windows 7 it's required administrator rights to change some parts of Windows Registry.
shExecInfo.lpVerb = L"runas"
意味着该进程将以提升的权限启动。如果您不想将其设置shExecInfo.lpVerb
为 NULL。但是在 Vista 或 Windows 7 下,更改 Windows 注册表的某些部分需要管理员权限。
回答by ralphtheninja
You need to read up on CreateProcess()in msdn. There's sample code on that page.
您需要阅读msdn 中的CreateProcess()。该页面上有示例代码。
回答by paxdiablo
If you just want to execute a synchronous command (run and wait), your best bet is to just use the system()
call (see here) to run it. Yes, I know it's a Linux page but C is a standard, no? :-)
如果您只想执行同步命令(运行并等待),最好的办法是使用system()
调用(请参阅此处)来运行它。是的,我知道这是一个 Linux 页面,但 C 是一个标准,不是吗?:-)
For more fine-grained control of what gets run, how it runs (sync/async) and lots more options, CreateProcess()
(see here), and its brethren, are probably better, though you'll be tied to the Windows platform (which may not be of immediate concern to you).
要更精细地控制运行的内容、运行方式(同步/异步)和更多选项CreateProcess()
(请参阅此处)及其兄弟,可能会更好,尽管您将绑定到 Windows 平台(这可能不是你的直接关注点)。
回答by sharptooth
Use CreateProcess() to spawn the process, check the return value to ensure that it started okay, then either close the handles to the process and the thread or use WaitForSingleObject() to wait until it finishes and then close handles.
使用 CreateProcess() 生成进程,检查返回值以确保它正常启动,然后关闭进程和线程的句柄或使用 WaitForSingleObject() 等待它完成然后关闭句柄。