Home » Programming Languages » C Programs » C Program to Execute Linux Commands

C Program to Execute Linux Commands

Following program shows how you can run some Linux commands from C program using C library API / system call named “system”. This API accepts a string which should be a command and its arguments which we want to execute on the console using C program.

$ vim run_command_with_system.c 
#include <stdlib.h>
#include <stdio.h>
 
#define COMMAND_TO_RUN "ps -ax"
 
int main(int argc, char **argv) {
        printf("Running ps with system\n");
        system(COMMAND_TO_RUN);
        printf("Done.\n");
        return 0;
}
 $ gcc -o run_command_with_system run_command_with_system.c 
 $ ./run_command_with_system 

This program will print the output of command “ps -ax” from C program.. if you want to execute any other command, you can just change it in #define COMMAND_TO_RUN , recompile and execute the program.

Man page of system : “man system”

DESCRIPTION
The system() library function uses fork(2) to create a child process that executes the shell command
specified in command using execl(3) as follows:

execl(“/bin/sh”, “sh”, “-c”, command, (char *) 0);

system() returns after the command has been completed.

During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored, in the
process that calls system() (these signals will be handled according to their defaults inside the child
process that executes command).

If command is NULL, then system() returns a status indicating whether a shell is available on the system


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment