Sample Header Ad - 728x90

flock not working between forks on the same fd

0 votes
1 answer
43 views
I am working on a process that forks several times. To debug it, I am using a debug file for which I open a fd and which stays the same for all child forks. Then I have a function print_debug, that will print to that fd. Now when the main process and the childs are printing at the same time, the output is intertwined in the debug file. I tried to solve that via a flock(fd, LOCK_EX), but that seems to have no effect. Here is an excerpt from the print_debug function:
void	print_debug(int fd, char *msg)
{
	
	flock(fd, LOCK_EX);
	print_debug2("... LOCK ACQUIRED ...");
    
    ... printing msg ...
    flock(fd, LOCK_UN);
}
Now when several forks print at the same time, the output looks like this:
--12692-- ... LOCK ACQUIRED ...
--12692-- fork no wait with fd_in 4, fd_out 1 and fd_close
----121269694-2-- - ..... . LOLOCKCK A ACQCQUIUIRERED D .....
.
----121269694-2-- - exriecghutt e sitrdeee o
f pipe started
--12694---- 12.69..2- - LO..CK.  ALOCQCUIK RACED Q..UI.
RE--D 12..69.4-
- --fd12 69ou2-t-  ifs orck urwreaintt
ly: 1
----121269692-4-- - ...... L LOCOCK K ACACQUQUIRIREDED . .....

----121269692-4-- - fofdrk o nuto  owan itcm wdit ch atfd i_is n cu0,rr fend_tlouy:t  15 
and fd_close
--126--9412--69 .6-..-  L..OC. K LOACCKQU AICQREUD IR..ED. .
.--.
12--69124-69- 6-er- rnexo ec2
ute tree
--1269--412--69 6-..- . ..LO.CK  ALOCCKQU IRACEQUDIR ED.. ..
.--.
12--6129694-6- --c fmdd_e oxutec iuts edcu rrfrenomtl y:ex ec5
Clearly, the printing of "lock acquired" overlap. I also controlled the return value of flock, which is always 0 (success). Does flock work in a situation like this? Why do I still have the issues of garbled messages in the log file?
Asked by Bastian (25 rep)
May 6, 2025, 08:09 PM
Last activity: May 11, 2025, 03:36 PM