Create directories in C using mkdir with proper permissions

2 min read >

Create directories in C using mkdir with proper permissions

Embedded & Engineering Insights

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 forget 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)
umask(process_mask);

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

Unlock innovation and digital transformation for your business.

Get in touch

We are always happy to talk

Phone

+40-21-223-7700

Email

hello@tremend.com

Address

165 Splaiul Unirii, Timpuri Noi Square,
TN Office 2 building, 4th floor,
District 3, Bucharest, Romania, 030134