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 Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense Multimedia - Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question