Open In App

exec family of functions in C

The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.h. There are many members in the exec family which are shown below with examples. 

Syntax: 

int execvp (const char *file, char *const argv[]);




//EXEC.c
 
#include<stdio.h>
#include<unistd.h>
 
int main()
{
    int i;
     
    printf("I am EXEC.c called by execvp() ");
    printf("\n");
     
    return 0;
}

gcc EXEC.c -o EXEC




//execDemo.c
 
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
        //A null terminated array of character
        //pointers
        char *args[]={"./EXEC",NULL};
        execvp(args[0],args);
     
        /*All statements are ignored after execvp() call as this whole
        process(execDemo.c) is replaced by another process (EXEC.c)
        */
        printf("Ending-----");
     
    return 0;
}

gcc execDemo.c -o execDemo
I AM EXEC.c called by execvp()

Syntax: 

int execv(const char *path, char *const argv[]);




//EXEC.c
 
#include<stdio.h>
#include<unistd.h>
 
int main()
{
    int i;
     
    printf("I am EXEC.c called by execv() ");
    printf("\n");
    return 0;
}

gcc EXEC.c -o EXEC




//execDemo.c
 
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
        //A null terminated array of character
        //pointers
        char *args[]={"./EXEC",NULL};
        execv(args[0],args);
     
        /*All statements are ignored after execvp() call as this whole
        process(execDemo.c) is replaced by another process (EXEC.c)
        */
        printf("Ending-----");
     
    return 0;
}

gcc execDemo.c -o execDemo
I AM EXEC.c called by execv()

Syntax: 

int execlp(const char *file, const char *arg,.../* (char  *) NULL */);
int execl(const char *path, const char *arg,.../* (char  *) NULL */);
int execvpe(const char *file, char *const argv[],char *const envp[]);

Syntax:
int execle(const char *path, const char *arg, .../*, (char *) NULL, 
char * const envp[] */);

Reference: exec(3) man page


Article Tags :