Duplicating (Whats Going On?)

File Descriptors, Open File, I-Node

File descriptor is a handle to a more complex structure inside the kernel

Open File

  • Offset

  • Flags

I-Node

  • Type

  • Block list

../../../../../../_images/filenum.svg

File Descriptors and Inheritance

  • A call to texttt{fork()} inherits file descriptors

  • ⟶ reference counted copy of the same Open File

  • ⟶ Processes share flags and offset!

  • File closed (open file freed) only when last copy is closed

../../../../../../_images/filenum-fork.svg

Duplicating File Descriptors

#include <unistd.h>

int dup(int oldfd);
  • Return: new file descriptor

#include <unistd.h>

int dup2(int oldfd, int newfd);
  • newfd already open/occupied ⟶ implicit close()

../../../../../../_images/filenum-dup.svg

Example: Shell Stdout-Redirection (1)

$ /bin/echo Hello > /dev/null
  • Redirection is a shell responsibility /bin/bash

  • echo writes “Hello” to standard output

  • … and does not want/have to care where it actually goes

Example: Shell Stdout-Redirection (2)

$ strace -f bash -c '/bin/echo Hallo > /dev/null'
[3722] open("/dev/null", O_WRONLY|O_...) = 3
[3722] dup2(3, 1) = 1
[3722] close(3) = 0
[3722] execve("/bin/echo", ...) = 0

(fork(), exec(), wait() omitted for clarity.)

Example: Shell Stdout-Redirection (3)

open("/dev/null")
../../../../../../_images/filenum-redir-1.svg
dup2(3, 1)
../../../../../../_images/filenum-redir-2.svg
close(3)
../../../../../../_images/filenum-redir-3.svg