Shell using Linux System calls in C
In this article we will be creating our own version of linux shell binary which provides the output based on the input commands provided.
Essentially we will be using the fork() system call to create a new process from the current shell which then execute the command passed. Once a new process is created execvp() func is used for replacing the complete current process stack with thew new command which is passed.
We start by printing the shell prompt inside the infinite while loop. Which completes a command and then returns back with the same statement. Use getline() funtion to read the input stream and use the strtok() function to divide it into tokens from the input.
getline(&cmd, &n, stdin);
token = strtok(cmd, delim);
int argc = 0; //counts no of args
while (token)
{
token = strtok(NULL, delim);
argc++;
}
Use the fork() system call to create a child process.
Child process created by the fork system call is identical to the parent process. But we want to replace the same with our desired process/program. Fork system call returns 0 in the child proces and actual pid in the parent process.
We check if the execution is in parent or child using if statement
if (pid == 0)
and then use execvp to replace the child process with the first argument from the input stream. For example if you passed ls -l then ls is the [0] argument in the array. Full array is also passed as the second parameter from which values starting with index 1 are taken as the arguments to the program/command passed.
execvp() takes care of the path varaibles while searching for the command.
int rt = execvp(argv[0], argv);
In the else statement we wait for the child to finish before the parent is allowed to complate using wait system call.
wait(NULL);
//building the binary
gcc shell.c -o myshell
//running the binary
./myshell
Github Code Link
Thank You!
