在C程序中执行Linux命令

23

我想在C程序中使用system系统调用来执行Linux命令,但是我不希望它将输出或错误日志转储到终端上。我该怎么办?还有其他方法吗?

4个回答

35

由于system()调用使用shell来执行命令,因此您可以将stdout和stderr重定向到/dev/null,例如:

system("ls -lh >/dev/null 2>&1");

10
+1,添加额外的 ); 是留给读者练习的 :) (说明:这是一句代码注释,意思是在代码中添加一个分号符号,但具体添加的位置需要读者自己思考并完成。) - Tim Post
1
我们需要一个头文件吗? - Shravya Boggarapu
1
@ShravyaBoggarapu 可能不需要,我没有加任何头文件也可以正常工作。 - Amir2mi
谢谢您的回复。虽然我不认为我甚至知道当时我在做什么的上下文。 - Shravya Boggarapu

22

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;
}

4
与其他答案不同,这个答案还可以获取程序的输出。 - Alexander Revo

6

展示你的代码。

例如,尝试以下代码:

system("ls");


5
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);
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接