使用单个 system() 调用在 C 中执行多个命令 [英] Using a Single system() Call to Execute Multiple Commands in C

查看:64
本文介绍了使用单个 system() 调用在 C 中执行多个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我工作的信息安全实验室中,我的任务是通过一次调用system()"(用 C 编写,在 Fedora 上运行)执行多个命令.允许我通过 system() 执行多于命令的语法是什么?(这个想法是,如果程序通过 system() 调用与操作系统交互,您可以通过在远程计算机上运行的程序执行任意命令.)

In an information security lab I'm working on, I've been tasked with executing multiple commands with a single call to "system()" (written in C, running on Fedora). What is the syntax that will allow me to execute more than command through system()? (The idea being you could execute arbitrary commands through a program running on a remote computer, if the program interacts with the OS through the system() call.)

即:

char command[] = "????? 
"; 
system(command);

推荐答案

这取决于被调用来执行命令的 shell,但通常大多数 shell 使用 ; 来分隔命令,所以像这样应该工作:

That depends on the shell being invoked to execute the commands, but in general most shells use ; to separate commands so something like this should work:

command1; command2; command3

正如@dicroce 提到的,您可以使用 && 而不是 ; 这将在返回非零值的第一个命令处停止执行.这可能需要也可能不需要(并且某些命令可能会在成功时返回非零值)但是如果您尝试处理可能失败的命令,您可能不应该在 system() 调用中将多个命令串在一起,因为您没有任何确定故障发生位置的方法.在这种情况下,您最好的选择是一次执行一个命令,或者创建一个 shell 脚本来执行适当的错误处理并调用它.

As @dicroce mentioned, you can use && instead of ; which will stop execution at the first command that returns a non-zero value. This may or may not be desired (and some commands may return non-zero on success) but if you are trying to handle commands that can fail you should probably not string multiple commands together in a system() call as you don't have any way of determining where the failure occured. In this case your best bet would either be to execute one command at a time or create a shell script that performs the appropriate error handling and call that instead.

这篇关于使用单个 system() 调用在 C 中执行多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆