How to execute a command in Linux using C program / C program to run linux command

 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

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply