I'm working on a linux C project and I'm having trouble working with file descriptors.
I have an orphan file descriptor (the file was open()'d then unlink()'d but the fd is still good) that has write-only permission. The original backing file had full permissions (created with S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), but alas the file was opened with O_WRONLY. Is it possible to duplicate the file descriptor and change the copy to O_RDWR?
psudo-code:
//open orphan file
int fd = open(fname, O_WRONLY, ...)
unlink(fname)
//fd is still good, but I can't read from it
//...
//I want to be able to read from orphan file
int fd2 = dup(fd)
//----change fd2 to read/write???----
Thanks in advance! -Andrew
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_RDWR))
seems like it would be the thing, except the man page specifically says that won't work. I guess there's some reason the kernel "needs" this to be impossible? – Jennee/dev/null
, i.e. discarding all further data written and just keeping a dummy file position. – RouletteO_WRONLY
flag before addingO_RDWR
.O_WRONLY|O_RDWR != O_RDWR
. – Roulettefcntl
call may not fail, but any attempt to read that fd will return an error, effectively settingerrno
toEBADF
. – Heteronomyfreopen
implemented then? Does it just fail? (It's allowed to fail.) – RouletteEBADF
too. If you want a reason for not allowing it, imagine changingstdin
to allow writes, andstdout
to allow reads - nonsense – Heteronomy/proc/self/fd/n
. See this stackoverflow answer for source code. – Hosbein