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?
Asked
Active
Viewed 9.7k times
4 Answers
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
-
10+1, Adding the additional `);` is an exercise left for the reader :) – Tim Post Jan 21 '11 at 22:23
-
1Do we need a header? – Shravya Boggarapu Jun 14 '18 at 13:44
-
1@ShravyaBoggarapu Probably no, it worked for me without any header. – Amir2mi Apr 25 '23 at 21:31
-
thank you for responding. although I don't think I even have the context of what I was working on at that time – Shravya Boggarapu Apr 26 '23 at 13:44
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
-
4Unlike other answers, this one also allows to get the program's output. – Alexander Revo Jun 16 '17 at 12:33
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