Commit cfe14e5503 for qemu.org
commit cfe14e550370100ebf27cfeea65f6b1b1e11004f
Author: Filip Hejsek <filip.hejsek@gmail.com>
Date: Sat Oct 17 01:09:09 2026 +0200
io: report a warning when a file channel is created from a stdio fd
A channel closes its fd when the last reference to it is dropped.
Closing stdio fds is typically unwanted, so warn when they are passed to
qio_channel_file_new_fd().
Change the documentation of qio_channel_file_new_fd() to explicitly say
that passing stdio descriptors is incorrect.
Signed-off-by: Filip Hejsek <filip.hejsek@gmail.com>
Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>
Reviewed-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Message-ID: <20261017-fix-stdio-close-v3-2-cfff0122a2a4@gmail.com>
diff --git a/include/io/channel-file.h b/include/io/channel-file.h
index d373a4e44d..6a6776ff8e 100644
--- a/include/io/channel-file.h
+++ b/include/io/channel-file.h
@@ -58,10 +58,14 @@ struct QIOChannelFile {
* should be used instead, as this provides greater
* functionality and cross platform portability.
*
- * The channel will own the passed in file descriptor
- * and will take responsibility for closing it, so the
- * caller must not close it. If appropriate the caller
- * should dup() its FD before opening the channel.
+ * The channel will own the file descriptor that was
+ * passed to it and will take responsibility for closing
+ * it. This means the caller must not close it, and must
+ * not pass in descriptors that will remain in use after
+ * the channel is destroyed. In particular, @fd must
+ * not be one of the stdin/stdout/stderr descriptors. If
+ * requiring a channel to wrap a descriptor that should
+ * remain open, use qio_channel_file_new_dupfd() instead.
*
* Returns: the new channel object
*/
diff --git a/io/channel-file.c b/io/channel-file.c
index 5cef75a67c..4c9da6619b 100644
--- a/io/channel-file.c
+++ b/io/channel-file.c
@@ -23,6 +23,7 @@
#include "io/channel-util.h"
#include "io/channel-watch.h"
#include "qapi/error.h"
+#include "qemu/error-report.h"
#include "qemu/module.h"
#include "qemu/sockets.h"
#include "trace.h"
@@ -32,6 +33,11 @@ qio_channel_file_new_fd(int fd)
{
QIOChannelFile *ioc;
+ if (fd <= STDERR_FILENO) {
+ warn_report("potential bug: creating a channel from stdio fd %d; "
+ "the fd will be closed when the channel is destroyed", fd);
+ }
+
ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE));
ioc->fd = fd;