如何在带有参数的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()
:
For a simple way, use system()
:
#include <stdlib.h>
...
int status = system("./foo 1 2 3");
system()
将等待foo完成执行,然后返回状态变量,可用于检查例如exitcode(命令的退出码乘以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()
的联机帮助页(在您的Linux系统)列出了可用于检查状态的各种宏,最有趣的是WIFEXITED
和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屋!