Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create directory with right permissions using C on Posix

Tags:

c

posix

mkdir

umask

I am trying to write a simple C program that creates directories (a mkdir clone.). This is what I have so far:

#include <stdlib.h>
#include <sys/stat.h> // mkdir
#include <stdio.h> // perror

mode_t getumask()
{
    mode_t mask = umask(0);
    umask (mask);
    return mask;
}

int main(int argc, const char *argv[])
{
    mode_t mask = getumask();
    printf("%i",mask);

    if (mkdir("trial",mask) == -1) {
        perror(argv[0]);
        exit(EXIT_FAILURE);
    }
    return 0;
}

This code creates directory with d--------- but I want it to create it with drwxr-xr-x like mkdir do? What am I doing wrong here?

like image 265
yasar Avatar asked Apr 13 '12 20:04

yasar


2 Answers

You seem to be misunderstanding what umask is used for. It sets/retrieves the process's file mode creation mask, which in turn is used to turn off bits in the file mode you specify in calls like mkdir, like this (pseduo-code):

real_mode = requested_mode & ~umask

So in your code, since you pass in the value of the umask itself, you end up specifying permissions as zero, which is exactly what you see.

Instead, you should specify the permissions you want in the call to mkdir, like this:

mkdir("trial", 0755)
like image 136
Eric Melski Avatar answered Oct 09 '22 15:10

Eric Melski


As Eric says, umask is the complement of the actual permission mode you get. So instead of passing mask itself to mkdir(), you should pass 0777-mask to mkdir().

like image 22
Crend King Avatar answered Oct 09 '22 17:10

Crend King