Skip to content

wrong behavior with fork and mmap #64256

Open

Description

@btiplitz
mannequin
BPO 20057
Nosy @vstinner, @bitdancer

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields:

assignee = None
closed_at = None
created_at = <Date 2013-12-23.21:05:18.990>
labels = ['type-bug', 'library']
title = 'wrong behavior with fork and mmap'
updated_at = <Date 2013-12-23.22:10:48.342>
user = 'https://bugs.python.org/btiplitz'

bugs.python.org fields:

activity = <Date 2013-12-23.22:10:48.342>
actor = 'btiplitz'
assignee = 'none'
closed = False
closed_date = None
closer = None
components = ['Library (Lib)']
creation = <Date 2013-12-23.21:05:18.990>
creator = 'btiplitz'
dependencies = []
files = []
hgrepos = []
issue_num = 20057
keywords = []
message_count = 5.0
messages = ['206871', '206872', '206876', '206877', '206878']
nosy_count = 3.0
nosy_names = ['vstinner', 'r.david.murray', 'btiplitz']
pr_nums = []
priority = 'normal'
resolution = None
stage = None
status = 'open'
superseder = None
type = 'behavior'
url = 'https://bugs.python.org/issue20057'
versions = ['Python 2.7']

Linked PRs

Activity

  1. btiplitz commented on Dec 23, 2013

    btiplitzmannequin
    MannequinAuthor

    When running the example mmap library (with a slight modification, plus I did not handle all the changes for the 3.3 string handling as the example posted does not work with 3.x)

    When looking at the subprocess, the spawned process will have all the mmap'd file descriptors open. The spawned process has the responsibility of closing any FD's that are in use. However, since the shared memory segment get's closed and the program has no knowledge of private FD's, the mmap's private FD becomes a leak in the FD table. It seems python should set the close-on-exec attribute on the dup'd FD that it maintains. Examples of fixing this issue are found on http://stackoverflow.com/questions/1643304/how-to-set-close-on-exec-by-default
    import mmap,os

    # write a simple example file
    with open("hello.txt", "wb") as f:
        f.write(bytes("Hello Python!\n", 'UTF-8'))
    
    with open("hello.txt", "r+b") as f:
        # memory-map the file, size 0 means whole file
        os.system("/bin/ls -l /proc/"+str(os.getpid())+"/fd")
    
        mm = mmap.mmap(f.fileno(), 0)
        os.system("/bin/ls -l /proc/"+str(os.getpid())+"/fd")
        os.system("/bin/ls -l /proc/self/fd")
    
        # read content via standard file methods
        t1 = mm.readline() # used to print out
      # prints "Hello Python!"
        # read content via slice notation
        t2=mm[:5]
    #    print mm[:5]  # prints "Hello"
        # update content using slice notation;
        # note that new content must have same size
        mm[6:] = bytes(" world!\n", 'UTF-8')
        # ... and read again using standard file methods
        mm.seek(0)
        t3=mm.readline()
     #   print mm.readline()  # prints "Hello  world!"
        # close the map
        mm.close()
    ~
  2. added
    stdlib
    type-bug
    on Dec 23, 2013
  3. bitdancer commented on Dec 23, 2013

    @bitdancer
    Member

    It seems very likely that this is addressed by PEP-446. Since that is not a behavior change that can be backported, I think this issue should probably be closed as out of date.

  4. btiplitz commented on Dec 23, 2013

    btiplitzmannequin
    MannequinAuthor

    Changing the code to
    subprocess.call(["/bin/ls", "-l", "/proc/self/fd"])
    and running this on Python 3.3 does show this as being resolved by the broader fix implemented in PEP-446. It does seem bad that the os.system call remains in place with bad behavior as I know it's widely used.

  5. vstinner commented on Dec 23, 2013

    @vstinner
    Member

    This issue is not specific to mmap. Many other functions and libraries may
    use private inheritable file descriptors. Python 3.4 does not fix the issue
    for third party libraries.

    os.system() must be avoided, use subprocess.call() instead. It avoids an
    useless shell process and closes all fds by default.

    Is it a documentation issue?

  6. btiplitz commented on Dec 23, 2013

    btiplitzmannequin
    MannequinAuthor

    Man page currently says as follows: (this does not says it's deprecated or that files have to be closed on exec)... So I'd think some more comments would help. And as mentioned, which a user can close his own fd's, the mmap call creates a special problem since the user can't work around the issue cleanly though fixed in the subprocess calls.

    s.system(command)
    Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.
    
    On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.
    
    On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation.
    
    The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.
    
    Availability: Unix, Windows.
    
  7. transferred this issue fromon Apr 10, 2022
  8. maurycy commented on Dec 5, 2026

    @maurycy
    Contributor

    PEP 446 (3.4) addressed the mmap case.

    The duplicate descriptor is inherited across fork() and closed at exec():

    2026-12-05T20:56:18.361761000+0100 maurycy@gimel /tmp  % cat 64256.py 
    import mmap, os, tempfile
    
    with tempfile.TemporaryFile() as f:
        f.write(b"x")
        f.flush()
        fd = os.dup(f.fileno())
        os.close(fd)  # mmap will get this descriptor number
        with mmap.mmap(f.fileno(), 0):
            print(os.path.samestat(os.fstat(fd), os.fstat(f.fileno())))
            print(os.get_inheritable(fd))
            print(os.system(f"test ! -e /dev/fd/{fd}"))
    2026-12-05T20:56:18.535993000+0100 maurycy@gimel /tmp  % uv run --python 3.14 python 64256.py 
    True
    False
    0

    cc @StanFromIreland

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions