[英]Execute a Linux command in the c program
我正在嘗試使用系統系統調用在 c 程序中執行 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;
}
給你看代碼。
嘗試例如:
系統(“ls”);
system()
和popen()
調用啟動一個 shell 並將它們的參數傳遞給它,這會產生安全漏洞。 除非根據 shell 的引用和轉義規則對源自用戶輸入的所有參數部分進行正確清理,否則攻擊者可能會在系統上運行任意命令。
相反,請使用exec
命令系列。 這些直接啟動命令,無需啟動 shell。 您可能仍然需要清理輸入,但只是為了限制可能傳遞給命令本身的內容。
來自SEI CERT C 編碼標准的示例:
#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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.