我想在C程序中使用system系统调用来执行Linux命令,但是我不希望它将输出或错误日志转储到终端上。我该怎么办?还有其他方法吗?
由于system()调用使用shell来执行命令,因此您可以将stdout和stderr重定向到/dev/null,例如:
system("ls -lh >/dev/null 2>&1");
popen 是另一种可以完成同样任务的方式:
void get_popen() {
FILE *pf;
char command[20];
char data[512];
// Execute a process listing
sprintf(command, "ps aux wwwf");
// Setup our pipe for reading and execute our command.
pf = popen(command,"r");
// Error handling
// Get the data from the process execution
fgets(data, 512 , pf);
// the data is now in 'data'
if (pclose(pf) != 0)
fprintf(stderr," Error: Failed to close command stream \n");
return;
}
展示你的代码。
例如,尝试以下代码:
system("ls");
system()
和 popen()
调用会启动一个 shell 并将其参数传递给它,这可能会导致安全漏洞。除非用户输入的参数经过正确的清理并符合 shell 的引用和转义规则,否则攻击者可能会在系统上运行任意命令。exec
命令系列。它们直接启动命令,而不是启动 shell。您仍然需要对输入进行清理,但仅限于限制可能传递给命令本身的内容。#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
void func(char *input) {
pid_t pid;
int status;
pid_t ret;
char *const args[3] = {"any_exe", input, NULL};
char **env;
extern char **environ;
/* ... Sanitize arguments ... */
pid = fork();
if (pid == -1) {
/* Handle error */
} else if (pid != 0) {
while ((ret = waitpid(pid, &status, 0)) == -1) {
if (errno != EINTR) {
/* Handle error */
break;
}
}
if ((ret == 0) ||
!(WIFEXITED(status) && !WEXITSTATUS(status))) {
/* Report unexpected child status */
}
} else {
/* ... Initialize env as a sanitized copy of environ ... */
if (execve("/usr/bin/any_cmd", args, env) == -1) {
/* Handle error */
_Exit(127);
}
}
}
);
是留给读者练习的 :) (说明:这是一句代码注释,意思是在代码中添加一个分号符号,但具体添加的位置需要读者自己思考并完成。) - Tim Post