H. Emre H. Emre - 4 years ago 83
Linux Question

unexpected result(-wS-wx--T) on file permission with open() function in C

I coded this program to open a file. Everything was OK when I saw this permission(-wS-wx--T) with

ls -lh


#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

#define FILE "open_1.txt"

int main()
int fd;
int errnum;

fd = open(FILE, O_RDWR | O_CREAT);

if(fd == -1)
printf("[error] There is a error\n");
perror("Error printed by perror");
}else {
printf("[succeeded] The process was succeeded\n");

return 0;

I compiled the program featly. I didn't take any error or warning.

$ ./open
[succeeded] The process was succeeded
$ ls -lh
-rwxrwxr-x 1 arien arien 8.5K Feb 1 23:38 open
--wS-wx--T 1 arien arien 0 Feb 1 23:39 open_1.txt

I haven't ever seen like this permission. I need some explanation.

Answer Source

If you include O_CREAT in the flags passed to open() then you must use the three-arg form of the function, which takes a numeric file mode as the third argument. This requirement is documented in the Linux manual page for the function (emphasis added):

The mode argument specifies the file mode bits be applied when a new file is created. This argument must be supplied when O_CREAT or O_TMPFILE is specified in flags; if neither O_CREAT nor O_TMPFILE is specified, then mode is ignored.

What mode you actually want is unclear, but perhaps S_IRUSR | S_IWUSR | S_IRGRP would be suitable (== 0640; read and write for the owner, read only for the owner's group, no permission for anyone else).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download