How To Run A Process From Another Process? [using system() function] - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

How To Run A Process From Another Process? [using system() function]

Share This

We know that Linux or Unix-like Operating System is a multi-tasking Operating System and an instance of a program constitutes a process.

In Linux, multiple processes can run simultaneously. Even multiple instances of the same program can execute simultaneously. Moreover, a process may initiate another process.

In the following example, we will discuss how a process can be executed from another process.


To discuss this topic, first, we should understand that when we run a command, a process is started. For example, if we execute ls command, a process is being started, which will be enlisted an in-process list of the Operating System.

If we run a C program, it will create another process. Hence, if we perform a system call from within a program, two processes will be executed.


In the following program, we have shown how ls -l command can be executed from a C program.
Source code to run a process inside another process
#include <stdlib.h> #include <stdio.h> int main() { printf("Running ls with system\n"); system("ls -l"); printf("Done.\n"); exit(0); }

In the above example, we have executed a process using ls -l command. After the call of the system function, the main process waits until the process gets completed. Hence, the Done message is printed after printing the output of the command.


In this context, if you want to run a process as a background process and you want to terminate the main process after starting another process, you can use & symbol at the end of the command you want to run. The example is shown below.
Source code to run a process inside another process
#include <stdlib.h> #include <stdio.h> int main() { printf("Running ls with system\n"); system("ls -l &"); printf("Done.\n"); exit(0); }

If you look at the output, you will understand that the main process is being terminated before the completion of another process.



Happy Exploring

No comments:

Post a Comment