tags:

views:

141

answers:

3

Is using fchmod(int fildes, mode_t mode) a better idea than using chmod(const char * path, mode_t mode)?

+5  A: 

It's pretty much identical. chmod will take ever so slightly little longer as it has to convert the path to an inode or filenode, whereas fchmod has the inode/filenode already looked up.

Of course, there are fewer error conditions which could occur with fchmod since the file is already known to exist, have permission for open, etc.

wallyk
A: 

If you are processing the contents of a file, you already have the file descriptor (either because you used open() to get it, or because you used fopen() and can use fileno() on the FILE * pointer to get it), you can use fchmod(). If you don't want to open the file for any processing but just change mode, use chmod().

Alok
+3  A: 

It depends on whether race conditions are a concern or not. With chmod you run the risk of someone renaming the file out from under you and chmodding the wrong file. In certain situations (especially if you're root) this can be a huge security hole.

Omnifarious
What if someone renames the file before you open the file descriptor to `fchmod`?
Alex B
Great point. I found http://www.mail-archive.com/[email protected]/msg00128.html for a real-world example. Thanks!
Alok
@Checkers, this is also a possibility. But after you open the file descriptor you can do fstat and compare the user and group id (or maybe look at the file data, or possibly even other tests) to make sure you got the right file. Also, in many cases you are chmodding a file you've created and so there is no race condition in the open call.
Omnifarious