Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a Linux command in the c program

Tags:

c

linux

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?

like image 483
hue Avatar asked Jan 21 '11 10:01

hue


People also ask

Can you use Linux commands in C?

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.

How do you call a UNIX command in C?

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.

Can you use UNIX commands in C?

We can run commands from a C program just as if they were from the UNIX command line by using the system() function.


2 Answers

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"); 
like image 138
nos Avatar answered Oct 15 '22 05:10

nos


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;
}
like image 28
TantrajJa Avatar answered Oct 15 '22 06:10

TantrajJa