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?
print_debug2()do exactly and is that a regular file you're writing to? On a common system, with a common stdio implementation, that constant string would be written in onewrite()system call, and on a regular OS, that write would be atomic. I.e. there shouldn't be interleaving between single letters. Can you turn your code into a small but complete example of the behaviour, with nothing but the necessary parts to show the issue?forkcopies the FD - see this StackOverflow post.