Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"creat" function gives wrong permissions

My code is as follows:

#include "unistd.h"
#include <fcntl.h>

#define BSIZE 50

int main(int argc, char *argv[]) {
    int f1, f2;
    char buf[BSIZE];

    f1 = open(argv[1], 0x0001, 0);
    f2 = creat(argv[2], 0777);

    read(f1, buf, BSIZE);
    write(f2, buf, BSIZE);

    return 0;
}

When I create a file named 'a' and use the compiled program with command

./a.out a b

It creates a file with the contents of 'a' indeed. But my problem is, its permissions are -rwxr-xr-x. It does not give write permissions to group and others. Moreover, when I change the function to creat(argv[2], 0022); then the permission would become all 0 s ----------.

Is there anything wrong with the creat function? Because chmod works fine.

like image 625
D. Jones Avatar asked Jan 23 '26 16:01

D. Jones


1 Answers

File creation uses two combined access permissions:

  1. the one you provided through creat or open
  2. and the process mask, aka umask

umask gives some final control to the user of your program by masking some bits to protect created files having some unexpected accesses. In general, umask equals to 022 means that write access is removed for group and others, i.e. users don't want more than rwxr-xr-x.

Then when you reclaim 0777 it is masked (and) with ~umask here 0755 giving 0755. When you reclaim 022 is is masked (and) with 0755 giving 000.

like image 181
Jean-Baptiste Yunès Avatar answered Jan 25 '26 11:01

Jean-Baptiste Yunès