Reputation: 877
I'm having a bunch of processes from different privileges, all running a shared code that open (and create if needed) a file for write using fopen_s with "a+" flag.
However, since no permissions that supplied to this command, and a root process create the file first, than other non-root processes couldn't access this file.
I could use int open(const char *pathname, int flags, mode_t mode);
and thus control the file permissions (represented by mode_t) to allow access for everyone, but I need the file descriptor (FILE *
) and not fileID. so I can use FILE *fdopen(int fd, const char *mode);
in order to make the conversion.
Perhaps there's a more straight forward way to do it ?
Upvotes: 0
Views: 628
Reputation: 1
I could use int open(const char *pathname, int flags, mode_t mode); and thus control the file permissions (represented by mode_t)
Not really. Unless you set your process's umask
setting. Because the permissions passed to open()
are not the permissions the created file is necessarily created with.
Per POSIX open()
(bolding mine):
the access permission bits (see
<sys/stat.h>
) of the file mode shall be set to the value of the argument following theoflag
argument taken as typemode_t
modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared.
So
int fd = open( someFileName, O_CREAT | O_RDWR, 0644 );
is NOT guaranteed to set the file permissions to 0644
.
If your file creation mask is set to 0077
, then the file will actually be created with permissions set to 0600
.
Note that the umask()
setting is a process-wide property, and it's not really a good idea to change it much. And if you're trying to write general-purpose code that has no side effects, it's a bad idea to change it at all. For example, changing the umask()
setting in a multithreaded process in order to allow wider access to files being created can cause
security problems if another thread creates a file at the same time.
The best way to set file permissions to be exactly what you want is to set file permissions to be exactly what you want with fchmod()
:
FILE *f = fopen(...);
fchmod( fileno( f ), 0644 );
In fact, since the umask()
setting is a process-wide property, it's always possible in general that it can be changed by another thread at any time, so setting the permissions explicitly via chmod()
or fchmod()
is the only guaranteed way to get exactly the permissions specified in all circumstances.
Upvotes: 1
Reputation: 130
No. The technique you described (open
followed by fdopen
) is the correct way to achieve what you want to do. As Some programmer dude pointed out, you could call chmod
from your program to change the file permissions after it's created, but that's a more roundabout way to do it.
Upvotes: 2