Google Interview Question
Site Reliability EngineersCountry: United States
Interview Type: Phone Interview
In plain english:
1. the system creates a subshell (via fork/exec of bash)
2. the stdout of the subshell is directed to the variable 'list'
3. ls is executed in the subshell
4. ls reads the dir_ent of the directory provided as an argument (or $PWD if none)
5. ls then returns this dir_ent listing to it's std out, and exits.
6. the subshell exits
This seems like not an algo interview question. From shell perspective, a new variable is created if list is not present. Command "ls" is executed and output is stored in list. If the list is present, then the old value is overridden. I am not sure what system calls are made or file descriptors are created.
You can observe that command at the system call layer by putting the command in a file (test.bash), and then running through strace:
Some highlights:
- You will see your strace command running the bash executable via the exec syscall
- The bash process will read the text file and interpret the commands.
- This bash process will create a pipe to read output from the subshell that $(command) creates
.
- The bash proces will call fork() (clone in linux) to create a subprocess for the subshell
- Parent process does a blocking read on the first file descriptor of the pipe (waiting to read output from the subshell)
- The new child process will use the second fd in the pipe for it's new stdout
- That new child pid will look for ls in the system path, then call exec() to run ls in the subshell process
- The ls program uses open() to open the current directory, then readdir() / getdents() to read the directory entries:
- Next, the ls command writes to stdout
- This wakes up the parent process blocked on the pipe (since child fd 1 is stdout, which was dup2'd to the second pipe fd 4)
26848 <... read resumed> "file1"..., 128) = 128
- The parent process waits for the child to exit, in case it hasn't already
- ajfabbri May 01, 2014