Cambiar los permisos de lectura / escritura en un descriptor de archivo

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

preguntado el 09 de enero de 11 a las 03:01

fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_RDWR)) parece 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? -

so why do you open it in wronly mode if you plan to read it? -

Odd, how is freopen implemented then? Does it just fail? (It's allowed to fail.) -

@R..: under Linux the very same rules apply. It isn't allowed to change access modes, and also doesn't return an error (in this case a NULL stream). Any attempt to read/write will cause EBADF too. If you want a reason for not allowing it, imagine changing stdin to allow writes, and stdout to allow reads - nonsense -

Yes, on Linux you can do this by opening /proc/self/fd/n. Ver this stackoverflow answer for source code. -

2 Respuestas

No, there is no POSIX function to change the open mode. You will need to open it in read / write mode. Since you are created a temporary file, though, I strongly recommend that you use mkstemp. That function properly opens the file in read/write mode and unlinks it. Most importantly, it avoids a race condition in naming and creating the file, thereby avoiding a vulnerability in the creation of temporary files.

Respondido el 09 de enero de 11 a las 07:01

mkstemp doesn't unlink AFAIK? - MK.

what MK said. I can always add O_EXCL to open() and retry on fail - Andrew Klofas

int fd = open(fname, O_WRONLY, ...)
int fd_ro = open(fname, O_RDONLY, ...)
unlink(fname)
{ write to fd }
close (fd);
read or execute(!) fd_ro

Respondido 21 Abr '18, 18:04

add some details please - Vinay Prajapati

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.