The behavior when simultaneously Simultaneously opening a file multiple times is has implementation-defined behavior. On some platforms, this is not allowed. On others, it might result in race conditions.
...
The following non-compliant code write example logs about the programs program's state at runtime.
| Code Block | ||
|---|---|---|
| ||
void do_stuff(void) {
FILE * logfile = fopen("log", "a");
/* Check for errors, write logs pertaining to do_stuff(), etc. */
}
int main(void) {
FILE * logfile = fopen("log", "a");
/* Check for errors, write logs pertaining to main(), etc. */
do_stuff()
/* ... */
}
|
However, it opens the file log is opened twice simultaneously. As stated above, the The result is implementation-defined and potentially dangerous.
Compliant Solution
...
| Code Block | ||
|---|---|---|
| ||
void do_stuff(FILE **file) {
FILE * logfile = *file;
/* Check for errors, write logs pertaining to do_stuff, etc. */
}
int main(void) {
FILE * logfile = fopen("log", "a");
/* Check for errors, write logs pertaining to main, etc. */
do_stuff(&logfile)
/* ... */
}
|
...