怎么呼叫一个外部程序与参数?
-
20-08-2019 - |
题
我谨呼吁windows程序在我的代码用参数内确定代码本身。
我不想叫外面的功能或方法,但实际的。exe或批量/脚本文件内WinXP环境。
C或C++将是优选的语言,但如果这是更加容易地做到在任何其他语言让我知道(ASM、C#蟒蛇,等等)。
解决方案
当你调用CreateProcess的(),系统()等,确保您的双引号的文件名字符串(包括命令程序的文件名)的情况下,你的文件名(S)和/或完全合格的路径有空格否则文件名路径的部分将被命令解释作为独立参数进行解析。
system("\"d:some path\\program.exe\" \"d:\\other path\\file name.ext\"");
有关视窗它建议使用的CreateProcess()。它有混乱的设置,但您对流程是如何启动(如由Greg Hewgill描述)的控制。为了快速和肮脏的,你也可以使用的WinExec()。 (系统()是便携式的,以UNIX)。
在启动批处理文件,你可能需要的cmd.exe(或command.com)推出。
WinExec("cmd \"d:some path\\program.bat\" \"d:\\other path\\file name.ext\"",SW_SHOW_MINIMIZED);
(或者如果要显示命令窗口SW_SHOW_NORMAL
)。
Windows应找到command.com或在系统PATH CMD.EXE所以不应该需要是完全合格的,但如果你想成为某些可以使用的 CSIDL_SYSTEM
(不只是使用C:\ Windows \ System32下\ cmd.exe的)。
其他提示
C ++示例:
char temp[512];
sprintf(temp, "command -%s -%s", parameter1, parameter2);
system((char *)temp);
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
}
}
我认为你正在寻找 CreateProcess的在Windows API函数。实际上有相关的呼叫的家庭,但是这将让你开始。这是很容易的。
一个最简单的方法来做到这一点是使用 system()
运行时图书馆功能。它需要一个单一串作为一个参数(其中许多参数比较少 CreateProcess
!) 并执行它,如果它是输入命令行。 system()
也自动地等待对于该进程完成之前返回。
也有局限性:
- 你有小控制的标准输入和输出的启动程
- 你不能做任何事情,而其他的运行过程(如决定要杀掉它)
- 你不能得到处理的其他程序,以查询它在任何方式
运行时的图书馆还提供了一个家庭 exec*
功能(execl
, execlp
, execle
, execv
, execvp
, 或多或更少),这是从Unix遗产和提供更多的控制的进程。
在最低水平,在Win32所有进程都推出了由 CreateProcess
功能,它给你的最大的灵活性。
简单的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 (); } }