使用 sysexits.h 定義的 EX_ 變數


以前我們常常在程式裡面直接呼叫 exit, 並搭配一個自己「想要」的變數作為程式的 return code,像是

exit(-1)

這樣的壞處是,我們不知道 0 代表什麼,-1 又代表什麼,這樣一來可讀性也會顯得比較差了一點。今天在無意之間看到 FreeBSD 的 lockf,他使用了 sysexits(3),在這邊節錄一下 man page 的敘述。

According to style(9), it is not a good practice to call exit(3) with
arbitrary values to indicate a failure condition when ending a program.
Instead, the pre-defined exit codes from sysexits should be used, so the
caller of the process can get a rough estimation about the failure class
without looking up the source code.

現在你可以改呼叫

exit(EX_USAGE)

這樣是不是好讀的多呢?


Leave a Reply

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