I just wrote a C application where I had to create a directory and let everyone read and write it.  That should be plain easy:

int result_code = mkdir("/usr/local/logs", S_IRWXU | S_IRWXG | S_IRWXO)

Apparently it’s a bit more complex, and I made a beginner’s error. I did forgot about the UMASK (http://www.tech-faq.com/umask.shtml).

Briefly: When you create a new file or directory, some of its permissions are restricted and cannot be set. Each process has a set of restrictions called the umask, and you must use the umask system call to disable or enable those restrictions. In my case, I set the umask to 0, that is no restrictions, created the directory, then restored the umask to its previous value:

mode_t process_mask = umask(0);
int result_code = mkdir("/usr/local/logs", S_IRWXU | S_IRWXG | S_IRWXO)

The code above is not reentrant and it gets a bit more complex if your program is multithreaded, but you get the idea.

One response to “Create directories in C using mkdir with proper permissions

  1. Hi, Bogdan!

    Thanks for this nice and (very) clarifying post!

    My colleagues encountered a similar problem (well, we are actually using Java, but for some system intricacies like the one you’re describing, we use JNI to call C modules/implementations) and I was rather circumspect about this (strange, at a first look) behavior. However, it seems that they were right :) (the problem was that when copying files (with ‘normal’ Java code), the exact file attributes of the source files were not kept.

    Thanks again.

Leave a Comment:

Your email address will not be published. Required fields are marked *