Skip to content

Coverage after fork seems not to be generated #1941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
MarkSymsCtx opened this issue Mar 26, 2025 · 2 comments
Closed

Coverage after fork seems not to be generated #1941

MarkSymsCtx opened this issue Mar 26, 2025 · 2 comments
Labels
bug Something isn't working

Comments

@MarkSymsCtx
Copy link

Describe the bug
If a python process uses os.fork it seems that even with concurreny=multiprocessing no coverage of the child process is generated. Example file below

To Reproduce
How can we reproduce the problem? Please be specific. Don't link to a failing CI job. Answer the questions below:

  1. What version of Python are you using?
    3.11
  2. What version of coverage.py shows the problem? The output of coverage debug sys is helpful.
    7.6.12
  3. What code shows the problem?
    This (not the nicest as it's just a quick hack to replicate some of our code)
#!/usr/bin/python3

import os
import tempfile
import time
import traceback

COMPLETE=tempfile.mkstemp()

print(f"Parent pid is {os.getpid()}")

pid = os.fork()
if pid:
    print(f"In parent, child is {pid}")
    try:
        while True:
            with open(COMPLETE[1], mode='r') as f:
                data = f.readline()

            print(f"Data is {data}")
            if "Complete" in data:
                print(f"Child is complete")
                break

            time.sleep(5)
    finally:
        wait_pid = 0
        while wait_pid == 0:
            wait_pid, rc = os.waitpid(pid, os.WNOHANG)
            if wait_pid == 0:
                time.sleep(2)
else:
    print(f"In child")
    time.sleep(10)
    print("Leaving child")
    with open(COMPLETE[1], mode='w') as f:
        f.write("Complete")
    os._exit(0)

Then run with coverage run -p --concurrency=multiprocessing test-fork-cover.py

Expected behavior
Expect to see coverage of both sides of the fork

@MarkSymsCtx MarkSymsCtx added the bug Something isn't working label Mar 26, 2025
@nedbat
Copy link
Owner

nedbat commented Mar 26, 2025

Does #310 provide a way to make it work?

@MarkSymsCtx
Copy link
Author

Yes, it does, thanks, swapping os._exit to sys.exit results in coverage being generated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants