When is umask() useful?

cpuer picture cpuer · Jun 1, 2011 · Viewed 19.1k times · Source
umask(0);

fd = open("/dev/null", O_RDWR);

Here's man 2 umask:

umask() sets the calling process’s file mode creation mask (umask) to mask & 0777.

But it doesn't make sense for me,as when we call open ,we will also provide a mode parameter.

So what's the point of umask?

Answer

Aaron Digulla picture Aaron Digulla · Jun 1, 2011

The umask is applied to all modes used in file system operations. From the manual open(2):

The permissions of the created file are (mode & ~umask)

So with a single call to umask, you can influence the mode of all create files.

This is usually used when a program wants the user to allow to overrule the default grants for files/directories it creates. A paranoid user (or root) can set the umask to 0077 which means that even if you specify 0777 in open(2), only the current user will have access.