Creating Linux Process using system() and difference between system() and fork() in C

In the previous chapters we saw what a process can be created in 3 different ways.

In this chapter we shall have a look at the first they using “system()” system call.

After this we shall have a look at difference between “system()” “fork()” and “exec()” system calls.

“system()”system call Introduction

Process creation using “system()” system call is one of the simplest way to create a process.

Below is the function prototype:

int system(const char *command);

You need to include below header to use the “ssytem()”

#include<stdlib.h>

How to create a process using “system()” system call.

system() will take command to be executed as an argument.
It will execute in the “sh” shell prompt.
system() is a blocking call, it will wait in the shell prompt till the command is executed.
system() will create a child process.
system() is considered as a security issue, because you can send any string as an argument and cause the system to crash.
system() will return non-zero value, if the command is a NULL pointer. Zero if the command is executed.

Example:

system(“ls -l”);

Example of creating a process using “system()” system call

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
#include <sched.h>

//for more tutorials on C, C++, STL, DS, Linux visit www.ProDeveloperTutorial.com

int main() 
{

	system("ls -l");

   return 0;
}

Output:

ProDevTutMacAir:~ aj$ ./a.out
total 168
drwx------@  4 aj  staff    128 Jul 12  2018 Applications
drwx------@ 20 aj  staff    640 Apr 22 10:36 Desktop
drwx------@ 26 aj  staff    832 Apr 12 21:26 Documents
drwx------@  8 aj  staff    256 Apr 22 22:19 Downloads
drwx------@ 18 aj  staff    576 Apr 18 07:49 Google Drive

Difference between fork(), exec() and system() system calls

We shall see the examples of fork() and exec() in upcoming chapters. You can revisit this section once you complete those chapters.

system()
* system() will take command as an argument and executes it in the shell.
* system() execution is different in different types of shell
* It is slower than fork() and exec().
* wildcards can also be used in system()

fork()
* fork() is used to create a new process that is a copy of parent process.
* fork() and exec() execution is system independent.

exec()
* exec is used to replace the existing process image with a new process.
* fork() and exec() are used in sequence while creating a process.

You can use “fork()”, “exec()” and “wait()” to emulate a “system()” system call.

Write a Comment

Leave a Comment

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