Page MenuHomeFreeBSD

fork.2: Make the example more robust
AbandonedPublic

Authored by 0mp on Apr 21 2021, 10:00 AM.
Tags
None
Referenced Files
Unknown Object (File)
Thu, Sep 26, 7:14 PM
Unknown Object (File)
Thu, Sep 26, 1:25 PM
Unknown Object (File)
Thu, Sep 26, 8:02 AM
Unknown Object (File)
Aug 27 2024, 10:38 PM
Unknown Object (File)
Aug 13 2024, 12:19 PM
Unknown Object (File)
Jul 29 2024, 11:19 AM
Unknown Object (File)
Jul 28 2024, 9:22 PM
Unknown Object (File)
Jul 16 2024, 11:04 AM
Subscribers

Details

Reviewers
kib
Group Reviewers
manpages
Summary

As noted by kib@:

Using printf around fork is not the best idea, and definitely should not
be provided as a guiding example in the man page. Using stdio safely around
fork() requires at least flushing buffers and ensuring that opened FILEs are
in some consistent state right at fork.

It would work by chance in your example, mostly because you did not use
anything in stdio before fork, but any further changes would result in
very puzzling bugs (for beginners, who are the target of this example).

Reported by: kib

Diff Detail

Repository
rS FreeBSD src repository - subversion
Lint
Lint Passed
Unit
No Test Coverage
Build Status
Buildable 38746
Build 35635: arc lint + arc unit

Event Timeline

0mp requested review of this revision.Apr 21 2021, 10:00 AM

@kib, I am not sure how to check if the FILEs are in a consistent state after fork. I was looking for examples in the base source code but I'm not sure what I'm looking for. Could you explain a bit more what should be in the manual page? Thanks!

lib/libc/sys/fork.2
127

In your example, fflush(stdout) should be done before fork, so that buffers are flushed only once. Otherwise e.g. a buffer would be printed both by child and the original process. exit() takes care of flushing.

Alternative is to not use stdio in the child, and to exit child with _exit() (ANSI C _Exit()) instead of exit(), which also does not flush buffers.