...
Code Block | ||||
---|---|---|---|---|
| ||||
errno = 0;
FILE* fd = fopen( filename, "r");
if (fd == NULL) {
char* errmsg = strerror(errno);
printf("Could not open file because of %s\n", errmsg);
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
errno = 0;
FILE* fd = fopen( filename, "r");
if (fd == NULL) {
char errmsg[BUFSIZ];
if (strerror_r(errno, errmsg, BUFSIZ) != 0) {
/* handle error */
}
printf("Could not open file because of %s\n", errmsg);
}
|
Note that Linux provides two versions of strerror_r()
, known as the XSI-compliant version and the GNU-specific version. This compliant solution assumes the XSI-compliant version. You can get the XSI-compliant version if you compile applications in the way POSIX requires (that is, by defining _POSIX_C_SOURCE
or _XOPEN_SOURCE
appropriately). Check your strerror_r()
manual page to see which version(s) are available on your system.
Compliant Solution (strerror_s)
The compliant solution uses the strerror_s()
function from Annex K of the C Standard, which has the same functionality as strerror()
but guarantees thread safety.
Code Block | ||||
---|---|---|---|---|
| ||||
errno = 0;
FILE* fd = fopen( filename, "r");
if (fd == NULL) {
char errmsg[BUFSIZ];
if (strerror_s(errno, errmsg, BUFSIZ) != 0) {
/* handle error */
}
printf("Could not open file because of %s\n", errmsg);
}
|
Note that because of the optional nature of Annex K, strerror_s()
may not be available in all implementations.
Risk Assessment
Race conditions caused by multiple threads invoking the same library function can lead to abnormal termination of the application, data integrity violations, or denial-of-service attack.
...