Thread-safe getopt() (was: report on not thread-safe functions)

From: Heikki Linnakangas <hlinnaka(at)iki(dot)fi>
To: Peter Eisentraut <peter(at)eisentraut(dot)org>, pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Thread-safe getopt() (was: report on not thread-safe functions)
Date: 2025-05-19 20:22:25
Message-ID: d1da5f0e-0d68-47c9-a882-eb22f462752f@iki.fi
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 06/06/2024 17:34, Peter Eisentraut wrote:
> Additionally, there are non-standard functions that are not
> thread-safe, such as getopt_long().

getopt_long() is not used in the server, only in client programs. The
server binary does actually accept a few "long" arguments, like --single
and --describe-config, but it has special code to handle them and
doesn't use getopt_long(). So we can leave getopt_long() alone for now.

> - getopt()
>
> This needs a custom replacement.  (There is no getopt_r() because
> programs usually don't call getopt() after startup.)
>
> (Note: This is also called during session startup, not only during
> initial postmaster start.  So we definitely need something here, if we
> want to, like, start more than one session concurrently.)

Here's a patch for a thread-safe version of getopt(). I implemented it
as two functions, pg_getopt_start() and pg_getopt_next(). Since there's
no standard to follow, we have freedom on how to implement it, and IMHO
that feels more natural than the single getopt() function. I took the
implementation from the getopt() replacement we already had for
platforms that don't have getopt(), moving all the global variables it
used to a struct.

The last patch attached replaces all calls in the server to use the new
variant, but leaves all the calls in client programs alone. I considered
changing the client programs as well, but there's no immediate need, and
it seems nice to use OS functions when possible.

(The first patch fixes a little harmless bug in get_stats_option_name()
that's gone unnoticed since 2006 but got in the way now.)

--
Heikki Linnakangas
Neon (https://neon.tech)

Attachment Content-Type Size
0001-Fix-latent-bug-in-get_stats_option_name.patch text/x-patch 1.0 KB
0002-Invent-custom-pg_getopt_ctx-that-is-thread-safe.patch text/x-patch 10.7 KB
0003-Replace-getopt-with-our-re-entrant-variant-in-the-ba.patch text/x-patch 18.6 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Peter Geoghegan 2025-05-19 20:29:09 Re: strange perf regression with data checksums
Previous Message Tomas Vondra 2025-05-19 20:17:16 Re: strange perf regression with data checksums