How to execute a command in Linux using C program ?

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");
        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”

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

How to create SSH Keys in Ubuntu / ... x
How to create SSH Keys in Ubuntu / Linux ?

Leave a Comment

Sign up to our newsletter!

ADB Commands Android Android Applications Android Build system Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia NDK / Middleware / HAL Operating System Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto Embedded Linux