Re:How can C Programs be so Reliable?
by JoachimSchipper on Thursday September 22, 2011 @09:09AM
(#3025906)
That is true, but good man pages still tend to document all or at least a lot of failure conditions. It's quite reasonable to do something like
if ((fd = open(myfile, O_RDWR | O_NONBLOCK, 0644)) == -1) {
switch(errno) {
case ENOENT: case ENOTDIR: case EACCESS:
case ELOOP: case ENAMETOOLONG: case EPERM:
warn("Cannot open file");
goto choose_file_to_open;
case EISDIR:
if (chdir(myfile) != 0)
warn("Failed to enter %s", myfile);
goto choose_file_to_open;
case ENXIO: case EWOULDBLOCK:
enqueue_open_callback(myfile);
return;
default:
err("Cannot open file");
}
The above is well-documented in open(2); compare, for instance, http://docs.python.org/library/os.html#os.open.
Re:How can C Programs be so Reliable?
by jemfinch on Thursday September 22, 2011 @09:58AM
(#3026068)
`os.open` is a low-level interface whose semantics are platform-dependent. The Python analogue is the builtin `open`, which documents that it raises IOError on a failure to open a file: http://docs.python.org/library/functions.html#open .
Re:How can C Programs be so Reliable?
by JoachimSchipper on Thursday September 22, 2011 @10:05AM
(#3026091)
True, but you have to dig a lot to find any details. The above code is easy to write from a good man page (OpenBSD's, in this case.)
(Also, open(2) has all these options for a reason; think symlink races. Python's open() is not sufficient.)
Re:How can C Programs be so Reliable?
by sausagefeet on Thursday September 22, 2011 @11:28AM
(#3026378)
Note, open is not part of C. A better comparison would be fopen which, according to the C99 draft I have, just returns NULL on failure.
Re:How can C Programs be so Reliable?
by JoachimSchipper on Thursday September 22, 2011 @12:41PM
(#3026663)
You're technically correct, but that's not the "C" being discussed in this article. Also, fopen(3) on OpenBSD does document values errno after failure (by reference to the malloc(3) and open(2) man pages), and I expect that any reasonable system does likewise.
Re:How can C Programs be so Reliable?
by cperciva on Thursday September 22, 2011 @05:27PM
(#3027883)
Sure. And you should certainly think about all the failure conditions listed in the man page and make sure you're handling them sanely. Just make sure that you don't forget to include the
default:
err("Cannot open file");
case.My biggest nightmare: debugging a chunk of badly documented C code that does not check return values to system calls at all...
Actually, no. When the documentation says
it doesn't mean that this is the only possible failure; POSIX states that functions "may generate additional errors unless explicitly disallowed for a particular function".Except in very rare circumstances, when you make system or library calls you should be prepared to receive an E_NEW_ERROR_NEVER_SEEN_NOR_DOCUMENTED_BEFORE and handle it sanely (which in most cases will involve printing an error message and exiting).