Here is process a
and b
, both of which are multithreaded.
a
forksb
andb
immediatly execs one new program;a
dup
s andfreopen
s stderr to the logfile (a
is defacto apache's httpd2.22)b
inherits the opened stderr froma
. ( i am adapting apache httpd,b
is my program), andb
usesfprintf(stderr....)
for logging- so
a
,b
share the same file for logging - there is no lock mechanism for
a
,b
to write log
I found that some log msg are interleaving, and a little bit of log msg got lost.
Can the two writers to the same file implicitly lock each other out?
The more important question is: If we use fprintf
only within one single multithreaded process, fprintf
is thread safe, i.e. one call of fprintf
won't intervene another fprintf
call in another thread? Many articles said this, but this is not easy to ensure myself, so I ask for help here.
A: the code for duplicate the fd is like this:
......
rv = apr_file_dup2(stderr_log, s_main->error_log, stderr_p);//dup the stderr to the logfile
apr_file_close(s_main->error_log);//here ,2 fd point to the same file description,so close one of
then
B:apache it self use this manner for logging:
......
if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s_main, ".........");
C:for convenience,i logging in this way:
fprintf(stderr,".....\n")
I am quite sure apache and me use the same fd for file writing.