Question

I used to open disk partitions using regular open call:

int fd = open("/dev/sdb1", O_RDWR);

However, when I have a number of Parted library calls in my source, the open call returns No such file or directory error, even when these Parted functions aren't actually called. For example, the code below:

#include <fcntl.h>
#include <unistd.h>
#include <parted/parted.h>
#include <cerrno> 
#include <cstring>
#include <iostream>

void find()
{
  PedDevice* pdev = ped_device_get("/dev/sdb");
}

void Out(const std::string& S, int R)
{
  std::cout << S << "\t" << R << "\t" << std::strerror(errno) << std::endl;
}

int main()
{
  int fd = open("/dev/sdb1", O_RDWR);
  Out("Opening  ", fd);
  int res = close(fd);
  Out("Closing  ", res);
}

outputs:

Opening     3   No such file or directory
Closing     0   No such file or directory

If just to comment the ped_device_get call out, then the program will output:

Opening     3   Success
Closing     0   Success

What's happening here?

(I'm on Ubuntu 3.11.0-15, which runs in VMware Fusion 6.0.2 on MacBook Pro)

Was it helpful?

Solution

This is really a StackOverflow answer. But since I've voted for migration there …

What's happening is that you've made a novice mistake:

the open call returns No such file or directory error

No, it did not. It returned the value 3, as you can easily see from the program output. That does not signify an error. Neither does the value 0 returned from close().

Only check and use the value of the errno macro if a function has indicated that it has set it. If open() had returned -1, indicating that it has set the value of errno, you could have legitimately interpreted the value of the macro as the error from the call. But since it didn't, you cannot.

Put another way: These functions do not reset the value of the errno macro upon success. They only set the value on failure.

The ENOENT error was from a previous failing system call somewhere. strace will probably tell you where. No doubt linking in that extra library causes initialization code to run before main().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top