soissy
soissy

Reputation: 78

C check if fd is open using write(2)

Is possible to know with system call write(2) if the fd that I'm sending data to is open or close?

My problem is that I'm writing to a fd that is sometimes closed and sometimes open. I think there must be a way to know with write this kind of situation but I can't find that.

Upvotes: 2

Views: 3310

Answers (2)

Ed Heal
Ed Heal

Reputation: 60027

From the manual page

On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.

So just check the return value for -1

Upvotes: 1

Déjà vu
Déjà vu

Reputation: 28850

You could use a system function that doesn't affect the file (if opened), instead of write, use fstat (man page)

int fstat(int fd, struct stat *buf);

Example

struct stat buf;
if (fstat(fd, &buf) == -1) {
    // fd is either closed or not accessible 
}

fstat() returns -1 if it couldn't use the file descriptor (0 otherwise).

Upvotes: 5

Related Questions