πŸ₯ƒExecuting system commands

In this section we shall see how to execute system commands using the exec functions

Link to exec function manual

Before we begin

#include <errno.h>

int main(int argc, char* argv[], char* envp[]){

    // argc = argument count
    // argv = argument vector
    // envp = environment pointer
    
    // errno stores the error code (if any) of the process in which the main thread is running

    return errno;
}

Let's first create a program to add any number of integers that are passed as arguments.

add.c
#include <stdio.h>
#include <math.h>
#include <string.h>

int str_to_int(char* c){
    int x = 0;
    int n = strlen(c);
    for(int i=0;i<n;i++)
        x += (c[i] - 48)*pow(10,n-i-1);
    return x;
}

int main(int argc, char* argv[]){
    int sum = 0;
    for(int i=1;i<argc;i++)
        sum += str_to_int(argv[i]);
    printf("Sum = %d",sum);
    return 0;
}

Now let's execute this program using certain arguments that are specified within the program itself.

Output

Note: We can't have more than one exec command in a program since the program will terminate on successful execution of the first exec function call that it encounters.

Another way we can do this is using the execvp function where we pass the list of arguments as an array.

Output

In case we want to execute a program from a path stored in ENVIRONMENT variables, we can use the execvp function.

Example:

Or we can just use the execl function

Output

In all cases the outputs are the same

Last updated