Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create file in C with full permissions for all

In my code, I have the following fragment:

char* filename="/something.txt";
umask(0);
int filehandle=open(filename,O_WRONLY|O_CREAT|0x777);
close(filehandle);

Upon executing it, the file is created but the permissions are not set correctly even though I followed documentation thoroughly.

Documentation states:

The argument mode specifies the permissions to use in case a new file is cre-ated. It is modified by the process's umask in the usual way: the permissions of the created file are (mode & ~umask).

and for the mode, I specified 0x777 which means read, write and execute. for umask, I specified zero so 0x777 & ~0 should result in 777.

The permissions that actually result are 670.

Why is that and how do I fix?

like image 765
Mike -- No longer here Avatar asked Oct 19 '15 02:10

Mike -- No longer here


Video Answer


1 Answers

For a start, it should be octal 0777 rather than hex 0x777, the equivalencies are:

0x777   0111 0111 0111   011 101 110 111   r-xrw-rwx, plus other stuff(a)
0777    111 111 111          111 111 111   rwxrwxrwx

Secondly, the signature is:

int open(const char *pathname, int flags, mode_t mode);

meaning that the mode is a separate argument, not something that you or with the flags.

Hence the line you're looking for would be:

int filehandle = open (filename, O_WRONLY | O_CREAT, 0777);

(a) I believe POSIX leaves those upper bits unspecified but Linux would use them to indicate that the file was setgid and sticky (though not in the original sense of sticky meaning code was kept cached in the swap space - Linux has never supported that, instead using the sticky bit to restrict who can perform certain operations on files within a sticky directory).

like image 121
paxdiablo Avatar answered Sep 26 '22 14:09

paxdiablo