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:

READ  How to resolve error : " no buildable Go source files in "

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

Leave a Reply

Your email address will not be published. Required fields are marked *