Gala Gala - 10 months ago 74
Linux Question

ioctl() call resets file descriptor to 0

Consider the following code:

file_fd = open(device, O_RDWR);

if (file_fd < 0) {
return -1;

printf("File descriptor: %d\n", file_fd);

uint32_t DskSize;

if (ioctl(file_fd, BLKGETSIZE, &DskSize) < 0) {
return -1;

printf("File descriptor after: %d\n", file_fd);

This snippet yields this:

File descriptor: 3
File descriptor after: 0

Why does my file descriptor get reset to 0? The program writes the stuff out to
instead of my block device.

This should not happen. I expect my
to be non-zero and retain its value.


Looks like you smash your stack.

Since there are only two stack variables file_fd and DskSize and changing DskSize changes file_fd suggests that DiskSize must be unsigned long or size_t (a 64-bit value), not uint32_t.

Looking at BLKGETSIZE implementation confirms that the value type is unsigned long.

You may like to run your applications under valgrind, it reports this kind of errors.