Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is /dev/null always openable?

Tags:

c

dev-null

I want to suppress certain fprintf calls by redirecting the destination FILE to /dev/null. But can I be sure, that fopen("/dev/null", "w"); NEVER returns NULL. In other words, is it everytime possible to open this "file"?

If so, I could use this nice ternary operator:

FILE *whereToPrint = (strcmp(custom_topic, ERROR_TOPIC) == 0) ? fopen("/dev/null", "w") : stdout;

fprintf(whereToPrint, "Message sent!\n\n");
like image 482
Michael Gierer Avatar asked Aug 24 '26 01:08

Michael Gierer


1 Answers

Yes, on a properly functioning system, /dev/null is world writable:

 ls -l /dev/null
 crw-rw-rw- 1 root root 1, 3 Jul 20  2017 /dev/null

So it'll always work. It's not the most efficient way to suppress output.. it would be better to simply not attempt to write if you don't want to.. but if it's not a lot of output, that won't matter.

Someone pointed out that it is possible for root to set the permissions of /dev/null so that it is not writable by other. Or they could delete the device altogether. This is true.. but it would result in a broken unix. /dev/null is supposed to have permissions as I showed above.. it is installed that way and should never be changed. Nevertheless, you should check the return value of fopen() or open() whenever opening any file.

like image 170
little_birdie Avatar answered Aug 26 '26 15:08

little_birdie