/**/ Difference between system() and execl() functions -

Difference between system() and execl() functions

In this post, we will discuss the difference between system() and execl() functions

execl() or execlp() functions replace the image of the current process with a new process image. In other words the current process code gets replaced by the new process code.

Syntax of execl()

                #include<unistd.h>
                int execl(const char *path, const char *arg, . . . /* (char *) NULL */);

Let us take an example:

Program 1:

#include<stdio.h>
int main()
{
         printf(“Before\n”);
         printf(After\n”);
} 

Output:

Before
After

Next if we introduce execl() function in the above code the output will change. This is because now the process image will get replaced.

Program 2:

#include<stdio.h>
#include<unistd.h>
int main()
{
printf(“Before\n”);
execl(“/bin/ps”,”ps”,NULL);
printf(After\n”);
} 

Output:

difference between system() and execl() functions in linux
execl( ) output

How it works?

Output of Program 1 is trivial. It prints both the printf() statements. In Program 2 the statement printf(“Before\n”) is printed and then execl() is called which replaces the current process image with the new process i.e. ps. Hence, the output of ps command is printed and not the second printf() statement. The output of ps also shows entry for ps only and not a.out (the original process) because the image of a.out is replaced by the image of ps process.

execl() can be used within a child process also to replace the image of the child process with a new process.

system() function in Linux

system() function on the other hand is used to execute a shell command from within a process.

Syntax:

                #include<stdlib.h>
                int system(const char *command);

In the background system() calls fork() to create a child process that executes the shell command specified in command using execl(3). In other words system will create a child process and replace its image with the image of a new process passed as its argument.

Program 3:

#include<stdio.h>
#include<stdlib.h>
int main()
{
                printf(“Before\n”);
                system(”ps”);
                printf(After\n”);
}

 Output:

system function in linux

How it works?

system() does not does not replace the image of the current process (a.out). So the first printf() gets printed then another process (ps) is created using system() which continues independently printing the output of ps command while a.out also continues and prints After using the second printf() statement. As seen from the out of ps command there were two process a.out (having PID 202) and ps (having PID 204).

Conclusion:

execl() system()
Replaces the image of the current process Does not replace the image of the current process
Does not create new process Creates a new process
   

Leave a Comment