jerrypeng
jerrypeng

Reputation: 94

What happens when you execute "ls" in Bash

Can some one provide me a detailed description of what happens when you execute the "ls" command in linux. What system calls are used? What does the file system do? Obviously depending on which file system is used. Is someone can provide an in depth discussion on this topic or point me to some good resources that would be great! Thanks!

Upvotes: 1

Views: 3226

Answers (2)

Rasul Osmanov
Rasul Osmanov

Reputation: 153

  1. Bash as command interpreter checks whether there such special words in it's own language: shell keywords or shell built-ins.
  2. ls isn't among shell keywords, then it checks aliases and replace alias with it's value, most likely there should be something like that: ls='ls --color=auto'
  3. it looks for ls executable in paths specified by PATH env variable. Usually it's /bin/ls
  4. It forks (fork()) new process and execs it's code (exec()). Process env is inherited from parent process to new "ls" process.
  5. New process becomes session leader and starts working on foreground (bash is moved to background)
  6. ls process loads shared libraries from LD_PATHs (ldd /bin/ls)
  7. it executes lots of systemcalls, you can check by strace, and the main part I believe are openat() and getdents() first opens directory and second reads entries inside there.
  8. prints output and exits, sends wait() signal and parent process bash terminates it completely.

Upvotes: 1

dormi330
dormi330

Reputation: 1353

  1. current process (we call parent process, or parent) find ls in $PATH variable,eg /usr/bin/ls
  2. parent(process) fork a child( process), and pass all enviroment, child process image is /usr/bin/ls
  3. without arguments, so child find env PWD, eg /foo/bar and excute (/usr/bin/ls /foo/bar)
  4. child process output , exit
  5. parent become interactive again

Upvotes: 0

Related Questions