Incomputable
Incomputable

Reputation: 2208

Is there a null file descriptor value in POSIX?

tl;dr Is there a posix descriptor value that I can throw into close() and nothing will happen?


Is there a specific value which I could use, like NULL for pointers, for file descriptors? I'd like the code to be uniform, so I thought that I could set the origin descriptor into null descriptor.

class socket
{
    int fd;
public:
    //deleted copy operations
    socket(socket&& other):
                   fd{other.fd}
    {
        other.fd = /*null descriptor*/
    }

    ~socket()
    {
        if (close(fd) == -1)
        {
            throw std::runtime_error{strerror(errno)};
        }
        // ^^ null file descriptor will do nothing on close()
        // like delete nullptr;
    }

I can store a boolean flag, but I'd like to avoid it.

The OS that it will be used on is Ubuntu 16.04, with gcc 5.4. I cannot use any library outside of POSIX and standard library itself, up to version present in gcc 5.4.

I tried to read man pages for open(), close(). They didn't mention any special value to use.

I tried to set it to -1, but I'm not sure if it is safe to use everywhere.

Upvotes: 2

Views: 2198

Answers (1)

SergeyA
SergeyA

Reputation: 62553

A minus 1 value for file descriptor can be used in close call with no detrimental effect on the application other than close returning -1 itself.

Since negative one is guaranteed to never be a valid file descriptor, it will be safe.

Upvotes: 6

Related Questions