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?
In the C programming standard library, there is a function named system () which is used to execute Linux as well as DOS commands in the C program.
An alternative to using system to execute a UNIX command in C is execlp. It all depends on the way you want to use them. If you want user input, then you might want to use execlp / execve. Otherwise, system is a fast, easy way to get UNIX working with your C program.
We can run commands from a C program just as if they were from the UNIX command line by using the system() function.
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");
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With