[PATCH] tools: iio: Keep the buffer index separate from the acquired fd
From: Zhu Jun
Date: Fri Nov 20 2026 - 01:19:15 EST
IIO_BUFFER_GET_FD_IOCTL takes the buffer index as input and replaces
it with a file descriptor on success. On failure, cleanup can mistake
the unchanged index for an open fd and close a different file. Only
assign the returned descriptor to buf_fd after successful acquisition.
Fixes: 8827faab2c8b ("tools: iio: convert iio_generic_buffer to use new IIO buffer API")
Signed-off-by: Zhu Jun <zhujun2@xxxxxxxxxxxxxxxxxxxx>
---
tools/iio/iio_generic_buffer.c | 12 +++++++-----
1 file changed, 7 insertions(+), 5 deletions(-)
diff --git a/tools/iio/iio_generic_buffer.c b/tools/iio/iio_generic_buffer.c
index 000193612aad..fd955cf444ad 100644
--- a/tools/iio/iio_generic_buffer.c
+++ b/tools/iio/iio_generic_buffer.c
@@ -404,7 +404,7 @@ int main(int argc, char **argv)
int ret, c;
struct stat st;
int fd = -1;
- int buf_fd = -1;
+ int buf_fd = -1, requested_fd;
int num_channels = 0;
char *trigger_name = NULL, *device_name = NULL;
@@ -714,11 +714,11 @@ int main(int argc, char **argv)
}
/* specify for which buffer index we want an FD */
- buf_fd = buffer_idx;
+ requested_fd = buffer_idx;
- ret = ioctl(fd, IIO_BUFFER_GET_FD_IOCTL, &buf_fd);
- if (ret == -1 || buf_fd == -1) {
- ret = -errno;
+ ret = ioctl(fd, IIO_BUFFER_GET_FD_IOCTL, &requested_fd);
+ if (ret < 0 || requested_fd < 0) {
+ ret = ret < 0 ? -errno : -EIO;
if (ret == -ENODEV || ret == -EINVAL)
fprintf(stderr,
"Device does not have this many buffers\n");
@@ -728,6 +728,8 @@ int main(int argc, char **argv)
goto error;
}
+ buf_fd = requested_fd;
+
/* Setup ring buffer parameters */
ret = write_sysfs_int("length", buf_dir_name, buf_len);
if (ret < 0)