<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://lambdapapers.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://lambdapapers.com/" rel="alternate" type="text/html" /><updated>2026-09-26T14:10:26+00:00</updated><id>https://lambdapapers.com/feed.xml</id><title type="html">λ Lambda Papers</title><subtitle>On Programming, Linux, Computer Science, and Mathematics. Curated with λove by an impostor.
</subtitle><author><name>Prajjwal Singh</name></author><entry><title type="html">Null Terminated Lists of Things in Bash</title><link href="https://lambdapapers.com/2020/01/29/null-terminated-lists-bash.html" rel="alternate" type="text/html" title="Null Terminated Lists of Things in Bash" /><published>2020-01-29T00:00:00+00:00</published><updated>2020-01-29T00:00:00+00:00</updated><id>https://lambdapapers.com/2020/01/29/null-terminated-lists-bash</id><content type="html" xml:base="https://lambdapapers.com/2020/01/29/null-terminated-lists-bash.html"><![CDATA[<p>You know the drill. You have to do something with a bunch of files, so you
<code class="language-plaintext highlighter-rouge">find</code> them and use <code class="language-plaintext highlighter-rouge">xargs</code> to do what you will.</p>

<div class="language-zsh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>find <span class="nt">-iname</span> <span class="s1">'*.tmp'</span> | xargs <span class="nb">rm</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">xargs</code> assumes whitespace separated input by default, which means that if
there’s a <code class="language-plaintext highlighter-rouge">this file.tmp</code> in there, <code class="language-plaintext highlighter-rouge">xargs</code> tries to do the following:</p>

<div class="language-zsh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">rm</span> <span class="s1">'this'</span>
<span class="nb">rm</span> <span class="s1">'file.tmp'</span>
</code></pre></div></div>

<p>That fails if you’re lucky. If you aren’t, some of those files really do exist
and get unintentionally deleted.</p>

<p>A favorable way of doing this is to remove ambiguity from the list of files
you’re passing around by making sure each filename is terminated by a <a href="https://en.wikipedia.org/wiki/Null_character">null
byte</a>. Because filenames on Linux
can never contain <code class="language-plaintext highlighter-rouge">NUL</code>, programs can safely assume that any characters
encountered before it are part of the filename and <em>not</em> a possible delimiter.
The following works correctly for filenames that contain whitespace or newlines:</p>

<div class="language-zsh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>find <span class="nt">-iname</span> <span class="s1">'*.tmp'</span> <span class="nt">-print0</span> | xargs <span class="nt">-0</span> <span class="nb">rm</span>
</code></pre></div></div>

<p>This is a standard idiom in any command line user’s repertoire.</p>

<p><code class="language-plaintext highlighter-rouge">find</code> and <code class="language-plaintext highlighter-rouge">xargs</code> aren’t the only two tools you’re used to that support this,
though, and that lets you do some cool things with confidence.</p>

<p><strong>Note:</strong> There are arguably better ways of doing this, such as using <code class="language-plaintext highlighter-rouge">find
-exec</code> or <a href="https://www.gnu.org/software/parallel/">GNU Parallel</a> in place of
<code class="language-plaintext highlighter-rouge">xargs</code>.</p>

<h2 id="example-passing-around-filenames-without-their-extension">Example: Passing around filenames without their extension</h2>

<p>You usually want to do this when you’re planning on converting one type of file
to another. The <code class="language-plaintext highlighter-rouge">basename</code> utility that lets us strip a trailing suffix from a
string supports <code class="language-plaintext highlighter-rouge">NUL</code> terminated output with the <code class="language-plaintext highlighter-rouge">-z</code> or <code class="language-plaintext highlighter-rouge">--zero</code> flags. I
commonly convert images and video as follows:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Repackage all '.mp4' files in the current directory as '.mkv'</span>
<span class="nb">basename</span> <span class="nt">-azs</span> .mp4 <span class="k">*</span>.mp4 | xargs <span class="nt">-0</span> <span class="nt">-I</span><span class="o">{}</span> ffmpeg <span class="nt">-i</span> <span class="o">{}</span>.mp4 <span class="se">\</span>
                           <span class="nt">-acodec</span> copy <span class="se">\</span>
                           <span class="nt">-vcodec</span> copy <span class="se">\</span>
                           <span class="o">{}</span>.mkv
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Convert all '.png' files in the current directory to '.jpg' with the same</span>
<span class="c"># name.</span>
<span class="nb">basename</span> <span class="nt">-azs</span> .jpg <span class="k">*</span>.jpg | xargs <span class="nt">-0</span> <span class="nt">-I</span><span class="o">{}</span> convert <span class="o">{}</span>.png <span class="o">{}</span>.jpg
</code></pre></div></div>

<h2 id="example-passing-around-files-containing-a-search-pattern">Example: Passing around files containing a search pattern</h2>

<p>Because every single program must come up with its own name for the same thing,
<code class="language-plaintext highlighter-rouge">grep</code> will output a null terminated list of files if you give it the <code class="language-plaintext highlighter-rouge">-Z</code> or
<code class="language-plaintext highlighter-rouge">--null</code> flags on the command line. Use that to delete all files in the current
working directory containing the word ‘consistency’ as follows:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">grep</span> <span class="nt">-s</span> <span class="nt">-lZ</span> <span class="s1">'consistency'</span> ./<span class="k">*</span> | xargs <span class="nt">-0</span> <span class="nb">rm</span>
</code></pre></div></div>

<h2 id="keeping-track-of-it-all">Keeping track of it all</h2>

<p>Because there’s so many different flags for this, I find it helpful to mentally
group programs that use the same one. Eg. the <code class="language-plaintext highlighter-rouge">sort</code>, <code class="language-plaintext highlighter-rouge">uniq</code>, <code class="language-plaintext highlighter-rouge">sed</code>, and
<code class="language-plaintext highlighter-rouge">basename</code> utilities all use <code class="language-plaintext highlighter-rouge">-z</code>.</p>

<p>Be warned, these can still have different multi character flags for the same
thing:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">basename --zero</code></li>
  <li><code class="language-plaintext highlighter-rouge">sort --zero-terminated</code></li>
  <li><code class="language-plaintext highlighter-rouge">uniq --zero-terminated</code></li>
  <li><code class="language-plaintext highlighter-rouge">sed --null-data</code></li>
</ul>

<p>This is why I drink.</p>

<p>~</p>]]></content><author><name>Prajjwal Singh</name></author><summary type="html"><![CDATA[You know the drill. You have to do something with a bunch of files, so you find them and use xargs to do what you will.]]></summary></entry><entry><title type="html">Exploring Linux File Locking Mechanisms in Ruby</title><link href="https://lambdapapers.com/2019/10/14/linux-file-locking-ruby.html" rel="alternate" type="text/html" title="Exploring Linux File Locking Mechanisms in Ruby" /><published>2019-10-14T00:00:00+00:00</published><updated>2019-10-14T00:00:00+00:00</updated><id>https://lambdapapers.com/2019/10/14/linux-file-locking-ruby</id><content type="html" xml:base="https://lambdapapers.com/2019/10/14/linux-file-locking-ruby.html"><![CDATA[<p><em>An exploration of File Locking mechanisms and their pitfalls on Linux in Ruby.</em></p>

<p>On a recent automation spree I produced a couple of hundred lines of ruby that
needed persistence. The built-in <code class="language-plaintext highlighter-rouge">PStore</code> is a natural choice for a project that
size. I’ve got two tasks that make destructive writes to the same <code class="language-plaintext highlighter-rouge">db.pstore</code>,
and both could potentially be scheduled together. Here’s what the documentation
has to say about that:</p>

<blockquote>
  <p>PStore objects are always reentrant. But if thread_safe is set to true, then
it will become thread-safe at the cost of a minor performance hit.</p>
</blockquote>

<p>But a <code class="language-plaintext highlighter-rouge">Mutex</code> isn’t helpful when you’ve got multiple <em>processes</em> writing to
the same resource on disk. Turns out, <code class="language-plaintext highlighter-rouge">PStore</code> also uses <code class="language-plaintext highlighter-rouge">File#flock</code> under the
hood, so if you’re in the middle of a write transaction, other processes trying
to transact will simply block, just like threads would in a thread-safe
environment. Let’s take a look at how it works.</p>

<h2 id="locking-files-with-flock">Locking Files with flock</h2>

<p>Consider the following piece of code, saved to a file <code class="language-plaintext highlighter-rouge">flock.rb</code>:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># flock.rb</span>

<span class="k">def</span> <span class="nf">log</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
  <span class="nb">puts</span> <span class="s2">"PID </span><span class="si">#{</span><span class="vg">$$</span><span class="si">}</span><span class="s2"> - </span><span class="si">#{</span><span class="n">msg</span><span class="si">}</span><span class="s2">"</span>
<span class="k">end</span>

<span class="k">def</span> <span class="nf">acquire_lock</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
  <span class="n">file</span><span class="p">.</span><span class="nf">flock</span><span class="p">(</span><span class="no">File</span><span class="o">::</span><span class="no">LOCK_EX</span><span class="p">)</span>
  <span class="n">log</span> <span class="s2">"acquired exclusive lock on db"</span>
<span class="k">end</span>

<span class="k">def</span> <span class="nf">write</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
  <span class="n">file</span><span class="p">.</span><span class="nf">write</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="vg">$$</span><span class="si">}</span><span class="s2"> was here last!"</span><span class="p">)</span>
  <span class="n">file</span><span class="p">.</span><span class="nf">flush</span>
<span class="k">end</span>

<span class="k">def</span> <span class="nf">print_file_contents</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
  <span class="n">file</span><span class="p">.</span><span class="nf">rewind</span>
  <span class="n">log</span> <span class="n">file</span><span class="p">.</span><span class="nf">read</span>
<span class="k">end</span>

<span class="n">log</span> <span class="s2">"started!"</span>

<span class="n">file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'datastore'</span><span class="p">,</span> <span class="no">File</span><span class="o">::</span><span class="no">CREAT</span> <span class="o">|</span> <span class="no">File</span><span class="o">::</span><span class="no">RDWR</span><span class="p">)</span>

<span class="n">acquire_lock</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="k">unless</span> <span class="no">ARGV</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="s1">'no_lock'</span>

<span class="n">write</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
<span class="nb">sleep</span> <span class="mi">10</span>
<span class="n">print_file_contents</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
</code></pre></div></div>

<p>The script acquires an exclusive lock(there’s also shared locks) and writes its
<code class="language-plaintext highlighter-rouge">PID</code> to it. The lock acquisition is skipped if you pass in <code class="language-plaintext highlighter-rouge">no_lock</code> as the
first command line parameter. If you open two terminal and run <code class="language-plaintext highlighter-rouge">ruby flock.rb</code>
in each, you will find that the process that starts second simply blocks until
the first process exists, and therefore each process prints out exactly what
<em>it</em> wrote to the file last. Now do that again, but invoke the second process as
follows <code class="language-plaintext highlighter-rouge">ruby flock.rb no_lock</code>. You’ll find that <em>process_2</em> doesn’t hesitate
writing its <code class="language-plaintext highlighter-rouge">PID</code> to the file, even though <em>process_1</em> is holding an exclusive
lock on it!</p>

<p>In practice, you would never see this because cooperating processes involved
would go through the correct <code class="language-plaintext highlighter-rouge">flock()</code> api.  Therefore, a few of you might find
this behavior unremarkable and perfectly acceptable.  We’ll get to that in a
second, but first let’s look at how <code class="language-plaintext highlighter-rouge">File#flock</code> actually works.</p>

<h2 id="fileflock-under-the-hood">File#flock Under The Hood</h2>

<p>A cursory inspection of the (ruby source) reveals that <code class="language-plaintext highlighter-rouge">File#flock</code> actually
uses the <code class="language-plaintext highlighter-rouge">flock(2)</code> system call. The <a href="https://linux.die.net/man/2/flock">manual</a>
defines it as follows:</p>

<blockquote>
  <p>flock - apply or remove an advisory lock on an open file</p>
</blockquote>

<p>Aha! So <code class="language-plaintext highlighter-rouge">File#flock</code> actually issues an advisory lock, which means that other
processes are free to ignore the locking protocol if they so desire. Advisory
locking is in contrast to <em>mandatory locking</em>, which prevents this sort of
thing from happening. Some environments, notably Windows(!), have certain
types of locks enforced by the filesystem by default! Ruby’s file locking
inherits all of <code class="language-plaintext highlighter-rouge">flock(2)</code>’s flaws:</p>

<ul>
  <li>Not cross-platform. The ruby documentation mentions this up front.</li>
  <li>No mandatory locking.</li>
  <li>Can only lock entire files. This is a big one. Imagine a heavily concurrent
system such as a database, with dozens of cooperating processes writing to
different parts of a file only being able to issue a single write at a time.</li>
</ul>

<p>Linux provides another locking mechanism that addresses those last two points,
which we’ll look at next.</p>

<h2 id="partial-locking-with-fcntl">Partial Locking with fcntl</h2>

<p>Due to the performance implications of issuing locks on entire files, most
systems provide mechanisms to lock only parts of a file. On Linux, this is
provided by the <code class="language-plaintext highlighter-rouge">fcntl()</code> system call. To quote <a href="https://en.wikipedia.org/wiki/The_Linux_Programming_Interface">The Linux Programming
Interface</a>:</p>

<blockquote>
  <p>This form of file locking is usually called <em>record locking</em>. However, this
term is a misnomer, because files on the UNIX system are byte sequences, with no
concept of record boundaries. Any notion of records within a file is defined
purely within an application.</p>
</blockquote>

<p>Ruby ships with a poorly documented interface for <code class="language-plaintext highlighter-rouge">fcntl()</code> if the underlying
system supports it. Let’s take a look at some basic usage:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># partial_lock.rb</span>

<span class="nb">require</span> <span class="s1">'fcntl'</span>

<span class="n">fd</span> <span class="o">=</span> <span class="no">IO</span><span class="p">.</span><span class="nf">sysopen</span><span class="p">(</span><span class="s1">'/tmp/datastore'</span><span class="p">,</span> <span class="no">Fcntl</span><span class="o">::</span><span class="no">O_WRONLY</span><span class="p">)</span>
<span class="n">f</span> <span class="o">=</span> <span class="no">IO</span><span class="p">.</span><span class="nf">open</span> <span class="n">fd</span>

<span class="n">pad</span> <span class="o">=</span> <span class="mi">0</span>

<span class="c1"># Acquire a lock for a 1 byte segment of the file starting at byte ARGV[0]</span>
<span class="c1"># [l_type, l_whence, l_start, l_len, l_pid]</span>
<span class="n">lock</span> <span class="o">=</span> <span class="p">[</span><span class="no">Fcntl</span><span class="o">::</span><span class="no">F_WRLCK</span><span class="p">,</span> <span class="no">IO</span><span class="o">::</span><span class="no">SEEK_SET</span><span class="p">,</span> <span class="n">pad</span><span class="p">,</span> <span class="no">ARGV</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="nf">to_i</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="vg">$$</span><span class="p">].</span><span class="nf">pack</span><span class="p">(</span><span class="s2">"s!s!i!L!L!i!"</span><span class="p">)</span>

<span class="n">f</span><span class="p">.</span><span class="nf">fcntl</span> <span class="no">Fcntl</span><span class="o">::</span><span class="no">F_SETLKW</span><span class="p">,</span> <span class="n">lock</span>

<span class="nb">puts</span> <span class="s2">"Acquired write lock"</span>

<span class="nb">sleep</span> <span class="mi">10</span>
</code></pre></div></div>

<p>The example is a bit obtuse because the lock is expressed as a binary string.
Fortunately Ruby’s excellent <code class="language-plaintext highlighter-rouge">Array#pack</code> takes the pain out of creating it.
The lock format is implementation dependent, so if the above code doesn’t work
for you, <code class="language-plaintext highlighter-rouge">man fcntl</code> should have the correct order of arguments. On my Linux
system, the code attempts to acquire a write lock for a 1 byte segment of the
file <code class="language-plaintext highlighter-rouge">/tmp/datastore</code> starting at at byte supplied on the command line. So,
<code class="language-plaintext highlighter-rouge">ruby partial_lock.rb 1</code> will acquire a lock on a segment spanning bytes 1 and
2.</p>

<p>Open two terminals and play around with this. You should find that acquiring a
lock on the same segment should block if another process is already holding a
lock, but the operating system happily issues it to you if you try to acquire it
on a different segment.</p>

<p>It is possible to issue a mandatory lock with <code class="language-plaintext highlighter-rouge">fcntl()</code>.</p>

<h2 id="playing-nice-with-external-processes">Playing Nice With External Processes</h2>

<p>Since <code class="language-plaintext highlighter-rouge">File#flock</code> uses <code class="language-plaintext highlighter-rouge">flock(2)</code> under the hood, it stands to reason that we
can cooperate with other non ruby processes. The following C program plays nice
with our <code class="language-plaintext highlighter-rouge">flock.rb</code>.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;sys/file.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;stdlib.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;fcntl.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;errno.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;unistd.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
	<span class="kt">int</span> <span class="n">fd</span><span class="p">,</span> <span class="n">lock</span> <span class="o">=</span> <span class="n">LOCK_EX</span><span class="p">;</span>

	<span class="n">fd</span> <span class="o">=</span> <span class="n">open</span> <span class="p">(</span><span class="s">"datastore"</span><span class="p">,</span> <span class="n">O_RDONLY</span><span class="p">);</span>

	<span class="k">if</span> <span class="p">(</span><span class="n">fd</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
		<span class="n">exit</span> <span class="p">(</span><span class="mi">1</span><span class="p">);</span>

	<span class="k">if</span> <span class="p">(</span><span class="n">flock</span> <span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">lock</span><span class="p">)</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
		<span class="k">if</span> <span class="p">(</span><span class="n">errno</span> <span class="o">==</span> <span class="n">EWOULDBLOCK</span><span class="p">)</span> <span class="p">{</span>
			<span class="n">puts</span> <span class="p">(</span><span class="s">"file is already locked!"</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="k">else</span> <span class="p">{</span>
			<span class="n">puts</span> <span class="p">(</span><span class="s">"could not acquire lock on file!"</span><span class="p">);</span>
		<span class="p">}</span>

		<span class="n">exit</span> <span class="p">(</span><span class="mi">1</span><span class="p">);</span>
	<span class="p">}</span>

	<span class="n">puts</span> <span class="p">(</span><span class="s">"acquired lock on file, sleeping for 10s"</span><span class="p">);</span>

	<span class="n">sleep</span> <span class="p">(</span><span class="mi">10</span><span class="p">);</span>

	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Polyglots rejoice!</p>

<h2 id="file-locking-in-shell-scripts">File Locking in Shell Scripts</h2>

<p>If your system supports <code class="language-plaintext highlighter-rouge">flock(2)</code>, in all likelihood it also ships with the
<code class="language-plaintext highlighter-rouge">flock</code> command line tool that lets you manage said locks in your shell scripts.
You can also use this to acquire a lock on an existing file descriptor, check
the manual for all sorts of examples. Try running the following on two separate
terminals:</p>

<div class="language-zsh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>flock <span class="s1">'/tmp/datastore'</span> <span class="nt">-c</span> <span class="s2">"echo start; echo hi &gt; /tmp/datastore; sleep 5; echo end"</span>
</code></pre></div></div>

<p>The second invocation should block until the first exits. Really handy!</p>

<h2 id="summary">Summary</h2>

<ul>
  <li>Ruby supports synchronized file operations with <code class="language-plaintext highlighter-rouge">File#flock</code>.</li>
  <li>It relies on the <code class="language-plaintext highlighter-rouge">flock(2)</code> system call, which isn’t available on all systems.</li>
  <li>It can only issue a lock on the entire file, which is terrible for massively
concurrent systems.</li>
  <li>It only issues advisory locks, which means external processes are free to
ignore it completely.</li>
  <li>Linux provides a non-portable way to issue locks on parts of a file via
<code class="language-plaintext highlighter-rouge">fcntl()</code>. These can also be made mandatory if the underlying FS supports it.</li>
  <li>The <code class="language-plaintext highlighter-rouge">flock</code> utility lets you manage said locks on the command line.</li>
</ul>

<p>Fin ~</p>]]></content><author><name>Prajjwal Singh</name></author><summary type="html"><![CDATA[An exploration of File Locking mechanisms and their pitfalls on Linux in Ruby.]]></summary></entry></feed>