What happens when you type ls -l in the shell?

What’s ls?

ls is a command used to list all the files and folders in the current directory.

Simply put it as if you opened a file and instead of having all the files in front of you, you need to pass the ls command to see what’s in there.

And what’s the -l ?

It’s basically an option for the ls, it stand for “long” and it’s used to make the shown files in a long format, as shown in the picture above.

So How The Shell Interact With The Command?

Before Typing the command there is the path that you are currently in, it’s also where the command ls will take action.

then there is the prompt and it can be in two types:

$ : which mean you are a normal user and have basic permissions.

# : The super user, as the name indicate you have all the privilege in the machine, even deleting the system files.

1- First of all it read all the command line by the function getline(), and save it for later.

2- Then it separate the command by the function strtok() to treat each part separately, and save in a double array.

example: if the command was “ls -la” it become {“ls”, “-la”, NULL}.

3- Now we have the command to execute which is “ls”, but it’s located in a different folder, so it need to locate it’s actual location in the global variable.

You can see all the global variable using the command env.

All the commands are located in the PATH directory, so all it need is locate it which directory it is.

In our case the “ls” is located in the “/bin” folder, so the path of ls is “/bin/ls”.

4- Now we have the path to the command and the options are in array, all we need is to execute it, well it’s not as simple as that, to execute a command in c you the system call execve().

But what’s a system call: it is a way for programs to interact with the operating system.

int execve(const char *pathname, char *const argv[], char *const envp[]);

pathname = “/bin/ls”

argv[] = {“ls”, “-la”, NULL}

envp = Array of environment variables.

But the execve will replace all the file with the command imputed, so we need a way that want discard our and that’s where the system call fork() come in.

What’s fork used for?

We can some all what the fork do in two simple steps:

1- create a duplicate file called the chilled containing all the functions that the parent have.

2- moving to the next line.

In other way we use fork to execute the execve without missing around with the parent file.

But then when compiling we need the wait system call so that the parent wait the chilled tell it finish it’s job.

And finally after executing the command all it need is to free all the allocated memory and then pass to the next line and print the prompt again waiting for the next command.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store