C++ 如何调用带参数的外部程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/486087/
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 call an external program with parameters?
提问by Will
I would like to call a windows program within my code with parameters determined within the code itself.
我想使用代码本身确定的参数在我的代码中调用 Windows 程序。
I'm not looking to call an outside function or method, but an actual .exe or batch/script file within the WinXP environment.
我不是要调用外部函数或方法,而是要调用 WinXP 环境中的实际 .exe 或批处理/脚本文件。
C or C++ would be the preferred language but if this is more easily done in any other language let me know (ASM, C#, Python, etc).
C 或 C++ 将是首选语言,但如果使用任何其他语言更容易做到这一点,请告诉我(ASM、C#、Python 等)。
采纳答案by Roger Nelson
When you call CreateProcess(), System(), etc., make sure you double quote your file name strings (including the command program filename) in case your file name(s) and/or the fully qualified path have spaces otherwise the parts of the file name path will be parsed by the command interpreter as separate arguments.
当您调用 CreateProcess()、System() 等时,请确保将文件名字符串(包括命令程序文件名)用双引号括起来,以防您的文件名和/或完全限定路径有空格,否则部分文件名路径的 将被命令解释器解析为单独的参数。
system("\"d:some path\program.exe\" \"d:\other path\file name.ext\"");
For Windows it is recommended to use CreateProcess(). It has messier setup but you have more control on how the processes is launched (as described by Greg Hewgill). For quick and dirty you can also use WinExec(). (system() is portable to UNIX).
对于 Windows,建议使用 CreateProcess()。它的设置更混乱,但您可以更好地控制进程的启动方式(如 Greg Hewgill 所述)。为了快速和肮脏,您还可以使用 WinExec()。(system() 可移植到 UNIX)。
When launching batch files you may need to launch with cmd.exe (or command.com).
启动批处理文件时,您可能需要使用 cmd.exe(或 command.com)启动。
WinExec("cmd \"d:some path\program.bat\" \"d:\other path\file name.ext\"",SW_SHOW_MINIMIZED);
(or SW_SHOW_NORMAL
if you want the command window displayed ).
(或者SW_SHOW_NORMAL
如果您希望显示命令窗口)。
Windows should find command.com or cmd.exe in the system PATH so in shouldn't need to be fully qualified, but if you want to be certain you can compose the fully qualified filename using CSIDL_SYSTEM
(don't simply use C:\Windows\system32\cmd.exe).
Windows 应该在系统 PATH 中找到 command.com 或 cmd.exe,因此不需要完全限定,但是如果您想确定可以使用CSIDL_SYSTEM
(不要简单地使用 C:\Windows \system32\cmd.exe)。
回答by Rorzilla
C++ example:
C++ 示例:
char temp[512];
sprintf(temp, "command -%s -%s", parameter1, parameter2);
system((char *)temp);
C# example:
C# 示例:
private static void RunCommandExample()
{
// Don't forget using System.Diagnostics
Process myProcess = new Process();
try
{
myProcess.StartInfo.FileName = "executabletorun.exe";
//Do not receive an event when the process exits.
myProcess.EnableRaisingEvents = false;
// Parameters
myProcess.StartInfo.Arguments = "/user testuser /otherparam ok";
// Modify the following to hide / show the window
myProcess.StartInfo.CreateNoWindow = false;
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
myProcess.Start();
}
catch (Exception e)
{
// Handle error here
}
}
回答by Mark Brittingham
I think you are looking for the CreateProcessfunction in the Windows API. There are actually a family of related calls but this will get you started. It is quite easy.
我认为您正在Windows API中寻找CreateProcess函数。实际上有一系列相关的调用,但这会让你开始。这很容易。
回答by Greg Hewgill
One of the simplest ways to do this is to use the system()
runtime library function. It takes a single string as a parameter (many fewer parameters than CreateProcess
!) and executes it as if it were typed on the command line. system()
also automatically waits for the process to finish before it returns.
执行此操作的最简单方法之一是使用system()
运行时库函数。它接受单个字符串作为参数(比CreateProcess
!少得多的参数)并像在命令行上键入一样执行它。system()
还会自动等待进程完成后再返回。
There are also limitations:
也有限制:
- you have less control over the stdin and stdout of the launched process
- you cannot do anything else while the other process is running (such as deciding to kill it)
- you cannot get a handle to the other process in order to query it in any way
- 您对启动进程的标准输入和标准输出的控制较少
- 当另一个进程正在运行时,你不能做任何其他事情(比如决定杀死它)
- 您无法获得其他进程的句柄以便以任何方式查询它
The runtime library also provides a family of exec*
functions (execl
, execlp
, execle
, execv
, execvp
, more or less) which are derived from Unix heritage and offer more control over the process.
运行时库还提供了一系列exec*
函数(execl
、execlp
、execle
、execv
、execvp
或多或少),这些函数源自 Unix 遗产并提供对过程的更多控制。
At the lowest level, on Win32 all processes are launched by the CreateProcess
function, which gives you the most flexibility.
在最低级别,在 Win32 上,所有进程都由该CreateProcess
函数启动,这为您提供了最大的灵活性。
回答by EnzoGuerra
simple c++ example (found after searching a few websites)
简单的 C++ 示例(搜索了几个网站后找到的)
#include <bits/stdc++.h>
#include <cassert>
#include <exception>
#include <iostream>
int main (const int argc, const char **argv) {
try {
assert (argc == 2);
const std::string filename = (const std::string) argv [1];
const std::string begin = "g++-7 " + filename;
const std::string end = " -Wall -Werror -Wfatal-errors -O3 -std=c++14 -o a.elf -L/usr/lib/x86_64-linux-gnu";
const std::string command = begin + end;
std::cout << "Compiling file using " << command << '\n';
assert (std::system ((const char *) command.c_str ()) == 0);
std::cout << "Running file a.elf" << '\n';
assert (std::system ((const char *) "./a.elf") == 0);
return 0; }
catch (std::exception const& e) { std::cerr << e.what () << '\n'; std::terminate (); }
catch (...) { std::cerr << "Found an unknown exception." << '\n'; std::terminate (); } }