Tutorial
Learner activity1 hands-on session

Why Deleting a File Doesn't Free the Disk: Inodes, File Descriptors, and truncate

Abed Pariazar
by  Abed Pariazar · on
Linux
A server runs out of disk space, you delete the biggest log file, and the disk stays full. Learn how Linux stores files and how processes keep them open, so you can free the space safely.

You delete a 5 GB log file to free up a full disk, and df still shows 100%. This happens on real servers, and the reason is in how Linux stores files and how processes use them.

In this tutorial, you will follow a file from its name to its data on the disk. You will see what a process holds when it opens a file, what rm and truncate change, and how to free the space that a deleted file still takes. Every step runs in the playground, so you can try each command right away.

This tutorial explains the concepts behind the challenge Free Up Disk Space on a Docker Host Without Downtime. You can read it before the challenge or come back to it when you get stuck.

Where files live

Linux keeps all files in one tree that starts at the root directory. The path of the root directory is /. Every directory in the tree has a typical role:

DirectoryWhat it holds
/etcConfiguration files
/homeThe home directories of regular users
/usrPrograms and libraries that do not change while the system runs
/varData that changes while the system runs, such as logs and caches
/var/logLog files of the system and of many services
/var/libState that programs keep between runs, for example /var/lib/docker for Docker
/tmpTemporary files
/procA virtual filesystem that shows the running processes and kernel data

The Linux manual page hier(7) describes these directories. For example, it says that /var holds files that may change in size, such as log files, and that /proc is the mount point for the proc filesystem. The Filesystem Hierarchy Standard says that /var/lib holds the state information of applications and of the system.

Most filesystems live on a disk or on a partition of a disk. Others live in memory, like tmpfs, come from another machine over the network, like NFS, or are created by the kernel, like the proc filesystem. Linux attaches each filesystem to a directory, and this directory is called a mount point. The root filesystem is mounted at /:

findmnt /
df -h /

Use df to see how full a filesystem is. It shows the space available on the filesystem that contains a path. The Avail column is the space that regular users can still use.

Where df gives totals, du adds up the space that files use, directory by directory. The -x flag keeps it on one filesystem, and --max-depth=1 shows one level of the tree:

sudo du -xh --max-depth=1 / | sort -h | tail -5

The ext4 filesystem keeps a part of the disk for the root user. According to the tune2fs manual page, this is the part that only privileged processes may allocate, and the default is 5%. When regular users see 0 bytes in the Avail column, root processes can still write a little. This is how an administrator can still log in and fix a full disk.

sudo tune2fs -l "$(findmnt -no SOURCE /)" | grep -i 'block count'

A file is a name, an inode, and data blocks

When you look at a file called app.log, you see one thing. Linux stores it as three parts:

  app.log            inode 48291             data blocks
  a name in a   -->  size, owner,       -->  the content
  directory          permissions,            of the file
                     number of links,
                     block locations
  • The name is an entry in a directory. It points to an inode.
  • The inode holds the metadata of the file: its size, owner, permissions, timestamps, the number of names that point to it, and the location of its data. Think of it as the identity card of the file. As the inode manual page sums it up, each file has an inode with its metadata.
  • The data blocks hold the content. A 5 GB log file usually takes 5 GB of data blocks, while its name and its inode take almost nothing. Sparse files are an exception, and a later section shows one.

Try it in the ~/lab directory:

cd ~/lab
echo "Hello Linux" > app.log
ls -li app.log

The first number in the output is the inode number. Rename the file and check the number again:

mv app.log new.log
ls -li new.log
stat new.log

The inode number stays the same, because a rename only changes the name. Run stat to see the rest of the inode, including the Links field.

A hard link is a second name for the same inode. Under the hood, ln calls the link system call, which creates a new name for an existing file:

echo "Hello" > original.log
ln original.log hard.log
ls -li original.log hard.log

Both names show the same inode number, and the link count is 2. The file has one inode and one set of data blocks, and two names point to it.

Once the task above is complete, remove one of the names and look at the other one:

rm original.log
ls -li hard.log
cat hard.log

The data is still there, and the link count went down to 1. So rm removed a name. The file itself stays for as long as something still refers to it.

Symbolic links work differently

A symbolic link is a small file of its own that stores the path of another file. It has its own inode, and it breaks when the target path disappears:

echo "Hello" > target.log
ln -s target.log soft.log
ls -li target.log soft.log
rm target.log
cat soft.log

The last command fails, because soft.log points to a name that no longer exists.

Open files: file descriptors

A process does not look up the name every time it reads or writes a file. It opens the file once and gets back a small number, which is called a file descriptor. From then on, it uses this number.

A process usually starts with three descriptors, which it inherits from its parent:

DescriptorNamePurpose
0stdinStandard input
1stdoutStandard output
2stderrStandard error

The kernel shows the descriptors of each process in the /proc/<pid>/fd directory. It has one entry for each file that the process has open. In Bash, $$ holds the PID of your current shell:

ls -l /proc/$$/fd

Open a file on descriptor 3 of your shell, write through it, and close it again:

exec 3>> ~/lab/notes.log
ls -l /proc/$$/fd
echo "written through fd 3" >&3
cat ~/lab/notes.log
exec 3>&-
What sits between a descriptor and the inode

A descriptor points to an open file description. This kernel object stores the current position in the file, which is called the offset, and the flags that the file was opened with. The manual page of open describes a descriptor as a reference to an open file description. The offset works like the cursor in a text editor. A normal read or write starts at the offset and moves it forward.

Append mode: > and >>

The shell opens the files of redirections, and it does that before the command starts. The Bash manual says that the shell handles redirections before a command is executed.

echo "first" > ~/lab/mode.log
echo "second" >> ~/lab/mode.log
cat ~/lab/mode.log
echo "third" > ~/lab/mode.log
cat ~/lab/mode.log

Most loggers that write to files use append mode, so new lines never overwrite old ones. This detail matters later, when you empty a log file that a process still writes to.

What rm does to a file

Behind the scenes, rm calls the unlink system call, which deletes a name from the filesystem. The kernel frees the inode and its data blocks only when two things are true: no name points to the inode, and no process holds the file open. An open file, says the unlink manual page, remains in existence until the last descriptor that refers to it is closed.

Reproduce it in your shell. Open a file on descriptor 3, write to it, and remove its name:

exec 3>> ~/lab/app.log
echo "Hello" >&3
rm ~/lab/app.log
ls -l /proc/$$/fd/3

The link ends with (deleted), but the file is still alive. Only the name is gone. The descriptor still leads to the inode through its open file description:

Before rm:

  app.log -----------------------------+
                                       v
  fd 3 --> open file description --> inode 48291 --> data blocks

After rm:

  fd 3 --> open file description --> inode 48291 --> data blocks

Write to it and read it back through the descriptor:

echo "I am still alive" >&3
cat /proc/$$/fd/3

Once the task above is complete, close the descriptor. This releases the last reference, and the kernel frees the file:

exec 3>&-

Why df and du disagree

When you run df, it asks the filesystem how many blocks are in use, so it also counts the blocks of deleted files that are still open. In contrast, du walks the directory tree and adds up the files that it finds there. A deleted file has no name in the tree, so du never sees it. When df reports much more used space than du can find, look for deleted files that are still open.

To find them, use lsof +L1. The manual page of lsof describes +L1 as the option that selects open files that have been unlinked:

sudo lsof +L1

For such files, the NLINK column shows 0, because no name points to them anymore.

What truncate does to a file

With truncate, you can shrink or extend a file to the size that you give it. With -s 0, it empties the file:

seq 1 100000 > ~/lab/big.log
ls -li ~/lab/big.log
truncate -s 0 ~/lab/big.log
ls -li ~/lab/big.log

The name and the inode stay the same, and only the size changes. Two details from the manual page of truncate matter here. The data beyond the new size is lost, and the file offset does not change. The freed blocks go back to the filesystem at once, even when a process holds the file open.

Why append mode matters here

A process that holds the file open keeps its own offset, and a truncation does not move it.

  • A writer in append mode writes at the current end of the file. After the truncation, the end of the file is byte 0, so the file starts to grow from there. Log writers such as the Docker daemon work this way.
  • A writer without append mode keeps writing at its old offset, for example at byte 1,000,000. The file gets a hole at the start and looks large in ls -l, although the hole takes no disk blocks.
See a file with a hole

A file with holes is called a sparse file. You can create one with truncate, and ls and du show different sizes for it:

truncate -s 1G ~/lab/sparse.img
ls -lh ~/lab/sparse.img
du -h ~/lab/sparse.img
rm ~/lab/sparse.img

Other ways to empty a file

Any command that opens a file with the O_TRUNC flag empties it in place:

: > ~/lab/big.log
cp /dev/null ~/lab/big.log
tee ~/lab/big.log < /dev/null > /dev/null

Since : is a command that does nothing, the > redirection alone empties the file. Copying the always empty /dev/null device over a file leaves zero bytes. In the last command, tee opens its file for writing and gets no input.

sudo and redirections

With sudo, you run a command as the superuser or as another user. A redirection belongs to the shell, and your shell runs as you. This is why the second command below fails with Permission denied, while the third one works:

sudo touch /var/log/lab-demo.log
sudo echo "hello" > /var/log/lab-demo.log
sudo sh -c 'echo "hello" > /var/log/lab-demo.log'
sudo cat /var/log/lab-demo.log
sudo rm /var/log/lab-demo.log

In the second command, your own shell opens the file before sudo starts. In the third command, sudo starts a root shell, and the root shell opens the file. This is not a problem for truncate, which opens the file itself, so sudo truncate -s 0 <file> works.

Exercise: free the space of a deleted file

A process called reporter runs on this server. It holds a 512 MiB file open, and someone has already deleted the name of this file. First, compare the used space that df reports with the total that du finds:

df -h /
sudo du -xsh /

The total from du is about half a gigabyte smaller, because du cannot see the deleted file. Find the process that holds the file and enter its PID below.

Hint 1: Finding deleted files

Try lsof +L1. It lists the files that are open but have no name. It needs root to see the files of all processes.

The reporter process must keep running. Free the space of the deleted file without stopping the process.

Hint 2: Reaching a file without a name

Every open file has an entry in /proc/<pid>/fd. In the output of lsof, the FD column shows the number of the descriptor, for example 3w. Opening that entry opens the file itself, even when its name is gone.

Docker logs on the host

Docker uses the json-file logging driver by default. This driver writes everything that a container prints into a JSON file on the host. To find the path of this file, ask docker inspect:

docker inspect -f '{{.LogPath}}' ticker
docker logs --tail 3 ticker

The Docker daemon holds this file open for as long as the container exists:

sudo ls -l /proc/$(pidof dockerd)/fd | grep json.log
Check that the daemon writes in append mode

Each descriptor also has an fdinfo entry, which shows its flags as an octal number. Use the descriptor number from the previous output:

sudo grep flags /proc/$(pidof dockerd)/fdinfo/<number>

In this value, the 02000 part is the O_APPEND flag. This is why new lines start at the beginning of the file after a truncation.

The json-file driver has no size limit unless you set one. Its max-size option defaults to -1, which means unlimited, and the Docker documentation notes that no log rotation happens by default. A container that prints a lot can fill the disk this way.

Important

The Docker documentation describes these log files as "designed to be exclusively accessed by the Docker daemon" and warns against touching them with other tools (JSON File logging driver). Emptying a log file with truncate is an emergency measure for a disk that is already full. On the Docker version of this playground, docker logs --tail stops answering for a container after its log file is emptied, until the container restarts. A plain docker logs call and the --since option keep working.

The lasting fix is log rotation with the options of Docker itself. In the /etc/docker/daemon.json file, these defaults apply to new containers:

{
  "log-driver": "json-file",
  "log-opts": { "max-size": "10m", "max-file": "3" }
}

Docker applies these settings only to the containers that are created after the daemon restarts. Existing containers keep their old logging settings until you recreate them.

Summary

A name points to an inode, and an inode points to data blocks. A process reaches the same inode through a file descriptor. Removing a file with rm takes away one name, and the space comes back only when no name and no descriptor refer to the inode. Truncating keeps the name and the inode and frees the data blocks at once.

GoalCommands
See the inode number of a filels -i, stat
See the open files of a processls -l /proc/<pid>/fd, lsof -p <pid>
Find deleted files that are still opensudo lsof +L1
Empty a file in placetruncate -s 0, : >, cp /dev/null
Empty a deleted file that is still opentruncate -s 0 /proc/<pid>/fd/<fd>
Find where the space wentdf -h, du -xh --max-depth=1

The challenge Free Up Disk Space on a Docker Host Without Downtime lets you practice all of this on a Docker host where nothing can be restarted.

References

Learn by doing, not just by reading or watching

Sign up for a free account to start a VM playground right on this page, track your progress, and get notified about new learning materials.

Sign up for free
About the author
Abed Pariazar

Abed Pariazar

I'm an infrastructure and DevOps engineer with 15+ years of running Linux servers in production, and I wholeheartedly believe in learning by teaching :)

Find this author online

More tutorials you might like
Start
Contents