如何使用参数在 linux 中的 C 代码中执行外部程序? [英] How do I execute external program within C code in linux with arguments?
问题描述
我想在 C 代码中执行另一个程序.比如我要执行一个命令
I want to execute another program within C code. For example, I want to execute a command
./foo 1 2 3
foo
为存在于同一文件夹中的程序,1 2 3
为参数.foo
程序创建一个将在我的代码中使用的文件.
foo
is the program which exists in the same folder, and 1 2 3
are arguments.
foo
program creates a file which will be used in my code.
我该怎么做?
推荐答案
简单的方法,使用system()
:
#include <stdlib.h>
...
int status = system("./foo 1 2 3");
system()
将等待 foo 完成执行,然后返回一个状态变量,您可以使用它来检查例如退出代码(命令的退出代码乘以 256,因此将 system() 的返回值除以它以获得实际的退出代码:int exitcode = status/256
).
system()
will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: int exitcode = status / 256
).
wait()
的手册页(在部分2, man 2 wait
on your Linux system) 列出了可以用来检查状态的各种宏,最有趣的是 WIFEXITED
和 WEXITSTATUS代码>.
The manpage for wait()
(in section 2, man 2 wait
on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be WIFEXITED
and WEXITSTATUS
.
或者,如果您需要读取 foo 的标准输出,请使用 popen(3)
,它返回一个文件指针 (FILE *
);与命令的标准输入/输出交互与读取或写入文件相同.
Alternatively, if you need to read foo's standard output, use popen(3)
, which returns a file pointer (FILE *
); interacting with the command's standard input/output is then the same as reading from or writing to a file.
这篇关于如何使用参数在 linux 中的 C 代码中执行外部程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!