testlib: Add an assertion that a fd has really been closed

We can't easily assert this without triggering warnings from tools like
valgrind by doing an invalid operation on a closed fd, so we only check
this when under `-m undefined`.

Originally contributed to GLib 2.76 in GNOME/glib@b3934133
"gstdio: Add g_clear_fd() and g_autofd". The implementation in GLib used
g_fsync() as a portable thing that we can do with a fd, but that
function is newer than our minimum GLib version, and libglnx isn't
portable to non-Unix anyway, so use fnctl() instead.

Signed-off-by: Simon McVittie <smcv@collabora.com>
This commit is contained in:
Simon McVittie
2026-03-05 16:01:43 +00:00
parent 1c391d734c
commit 606dbdbc20
2 changed files with 23 additions and 1 deletions

View File

@@ -23,6 +23,7 @@
#include "libglnx-testlib.h"
#include <errno.h>
#include <fcntl.h>
#include <glib/gstdio.h>
@@ -72,3 +73,21 @@ _glnx_test_auto_temp_dir_leave (_GLnxTestAutoTempDir *dir)
g_free (dir->old_cwd);
g_free (dir);
}
void
_glnx_test_assert_fd_was_closed (int fd)
{
/* We can't tell a fd was really closed without behaving as though it
* was still valid */
if (g_test_undefined ())
{
int result;
int errsv;
errno = 0;
result = fcntl (fd, F_GETFD, 0);
errsv = errno;
g_assert_cmpint (result, <, 0);
g_assert_cmpint (errsv, ==, EBADF);
}
}

View File

@@ -1,7 +1,7 @@
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
*
* Copyright (C) 2017 Red Hat, Inc.
* Copyright 2019 Collabora Ltd.
* Copyright 2019-2022 Collabora Ltd.
* SPDX-License-Identifier: LGPL-2.0-or-later
*
* This library is free software; you can redistribute it and/or
@@ -23,6 +23,7 @@
#pragma once
#include <glib.h>
#include <glib/gstdio.h>
#include "glnx-backport-autoptr.h"
@@ -47,3 +48,5 @@ G_DEFINE_AUTOPTR_CLEANUP_FUNC(_GLnxTestAutoTempDir, _glnx_test_auto_temp_dir_lea
#define _GLNX_TEST_SCOPED_TEMP_DIR \
G_GNUC_UNUSED g_autoptr(_GLnxTestAutoTempDir) temp_dir = _glnx_test_auto_temp_dir_enter ()
void _glnx_test_assert_fd_was_closed (int fd);