title - Do not simultaneously open a file multiple times
The behavior when simultaneously opening a file multiple times is implementation defined. On some platforms, this is not even allowed. On others, it might result in race conditions.
Non-Compliant Coding Example
The following non-compliant code opens the file log twice concurrently.
| Code Block | ||
|---|---|---|
| ||
void do_stuff(void) { FILE* logfile = fopen("log", "a"); /* openCheck logfor fileerrors, write logs pertaining to do_stuff, call log_function, open log file, write */ |
Compliant Solution
etc. */
}
int main() {
FILE* logfile = fopen("log", "a");
/* Check for errors, write logs pertaining to main, etc. */
do_stuff()
/* ... */
}
|
Compliant Solution
In this compliant solution, a reference to the file pointer is passed around so that the file does not have to be opened twice separately.
| Code Block | ||
|---|---|---|
| ||
void do_stuff(FILE **file) { FILE* logfile = *file; /* pass around FILE **file_ptr */ Check for errors, write logs pertaining to do_stuff, etc. */ } int main() { FILE* logfile = fopen("log", "a"); /* Check for errors, write logs pertaining to main, etc. */ do_stuff(&logfile) /* ... */ } |
Risk Assessment
Simultaneously opening a file multiple times could result in abnormal program termination or a data integrity violation.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
FIO08-A | 2 (medium) | 2 (probable) | 2 (medium) | P8 | L2 |
References
| Wiki Markup |
|---|
\[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] Section 7.19.3, "Files" |