23

I am trying to execute a Linux command in c program using system system call, but the don't want it to dump the output or error logs on the terminal. What should I do? Is there any other way to do this?

TheCodeArtist
  • 21,479
  • 4
  • 69
  • 130
hue
  • 1,759
  • 3
  • 27
  • 37

4 Answers4

35

As the system() call uses a shell to execute the command, you can redirect stdout and stderr to /dev/null, e.g.

system("ls -lh >/dev/null 2>&1");
nos
  • 223,662
  • 58
  • 417
  • 506
22

popen is another way in which you can do the same:

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;
}
Shane Welsh
  • 3
  • 1
  • 3
TantrajJa
  • 1,987
  • 2
  • 15
  • 9
6

Show you code.

Try for example:

system("ls");

0xAX
  • 20,957
  • 26
  • 117
  • 206
5

The system() and popen() calls start a shell and pass their arguments to it, which creates security vulnerabilities. Unless all parts of the arguments originating from user input are correctly sanitized according to the shell's quoting and escaping rules, an attacker can probably run arbitrary commands on the system.

Instead, use the exec family of commands. These start the command directly, without starting a shell. You may still need to sanitize the input, but only to limit what may be passed to the command itself.

Example from the SEI CERT C Coding Standard:

#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);
    }
  }
}
Roger Dahl
  • 15,132
  • 8
  • 62
  • 82