Question

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?

Was it helpful?

Solution

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().

OTHER TIPS

To add to the answer, in The C Programming Language book (K&RC) they have given a small example on how to go about implementing ls. They have explained the datastructures and functions used very well.

To understand what ls does, you could take a gander at the OpenSolaris source: https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/cmd/ls/ls.c.

If that´s overwhelming, on Solaris you start by using truss to look at the system calls that ls makes to understand what it does. Using truss, try:

truss -afl -o ls.out /bin/ls

then look at the output in ls.out

I believe that trace is the equivalent to truss in Linux.

If you really want to understand the detailed innards of ls, look at the source code. You can follow tpgould's link to the Solaris source, or it's easy to find the source online from any Linux or BSD distribution.

I'll particularly recommend the 4.4BSD source.

As I recall, ls starts by parsing its many options, then starts with the files or directories listed on the command line (default is "."). Subdirectories are handled by recursion into the directory list routine. There's no fork() or exec() that I recall.

This is a old thread , but still I am commenting because I believe the answer which was upvoted and accepted is partially incorrect. @Mark says that ls is built into shell so shell doesn't exec and fork. When I studied the tldp document on bash(I have attached the link) "ls" is not listed as a build in command.

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_01_03.html

Bash built-in commands:

alias, bind, builtin, command, declare, echo, enable, help, let, local, logout, printf, read, shopt, type, typeset, ulimit and unalias.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top