How does the 'ls' command work in Linux/Unix?

iankits picture iankits · Oct 15, 2008 · Viewed 33.8k times · Source

I would like to know exactly how the "Is" command works in Linux and Unix.

As far as I know, ls forks & exec to the Linux/Unix shell and then gets the output (of the current file tree. eg./home/ankit/). I need a more detailed explanation, as I am not sure about what happens after calling fork.

Could anyone please explain the functionality of the 'ls' command in detail?

Answer

Mark Baker picture Mark Baker · Oct 15, 2008

ls doesn't fork. The shell forks and execs in order to run any command that isn't built in, and one of the commands it can run is ls.

ls uses opendir() and readdir() to step through all the files in the directory. If it needs more information about one of them it calls stat().