I am writing a program to mimic the cp utility. However, I cannot get the file permissions to work correctly. I know that they are stored in the structure stat
and stored in the st_mode
field with stat
.
My issue is that I do not get the write permission for the group or other categories, i.e. I get -rwxr-xr-x
as the permissions for the file even though the source file is -rwxrwxrwx
. The statement where I set the permissions is below.
if ( (dest_fd = open(dest_file, O_WRONLY|O_CREAT, (stats.st_mode & S_IRUSR)|(stats.st_mode & S_IWUSR)|(stats.st_mode & S_IXUSR)|(stats.st_mode & S_IRGRP)|(stats.st_mode & S_IWGRP)|(stats.st_mode & S_IXGRP)|(stats.st_mode & S_IROTH)|(stats.st_mode & S_IWOTH)| (stats.st_mode & S_IXOTH))) < 0)
{
printf("There was a problem opening the destination file.");
exit(EXIT_FAILURE);
}//ends the if statement opening the destination file.
The answers so far are right that the problem is umask
, but rather than clearing the umask
(this is dangerous if your program is multi-threaded or if you might be calling any library functions that create files) I would treat the umask
as a user configuration variable you are not allowed to modify, and instead call fchmod
on the files after creating them to give them the final permissions you want. This may be necessary anyway to give certain permissions like suid/sgid, which some kernels remove whenever the file is modified. I would also initially create the file with mode 0600
, so that there's no race condition between opening it and changing permissions during which another user could get an open handle on the file.