This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author giampaolo.rodola
Recipients giampaolo.rodola, njs, vstinner
Date 2019-11-14.03:19:21
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1573701562.46.0.241782603067.issue38630@roundup.psfhosted.org>
In-reply-to
Content
To further elaborate on the creation time solution, the idea in pseudo-code is the following:

class Popen:

    def __init__(self, ...):
        self._execute_child(...)
        try:
            self._ctime = get_create_time(self.pid)
        except ProcessLookupError:
            self._ctime = None

    def send_signal(self, sig):
        if self._ctime is not None:
            if self._ctime != get_create_time(self.pid):
                raise ProecssLookupError("PID has been reused")
        os.kill(self.pid, sig)

Technically there is still a race condition between _execute_child() and get_create_time(), but:

1) the time between the two calls is supposed to be extremely short
2) an OS should not reuse a PID that fast, precisely in order to minimize the chances of such a race condition to occur
3) as a general rule, on most systems PIDs are supposed to be assigned sequentially and wrap around. E.g. on Linux:

~$ for i in $(seq 20); do ps; done | grep ps
3199 pts/0    00:00:00 ps
3200 pts/0    00:00:00 ps
3201 pts/0    00:00:00 ps
3202 pts/0    00:00:00 ps
3203 pts/0    00:00:00 ps
3204 pts/0    00:00:00 ps
3205 pts/0    00:00:00 ps
3207 pts/0    00:00:00 ps
3208 pts/0    00:00:00 ps
3209 pts/0    00:00:00 ps
3210 pts/0    00:00:00 ps
3213 pts/0    00:00:00 ps
3214 pts/0    00:00:00 ps
3215 pts/0    00:00:00 ps
3216 pts/0    00:00:00 ps
3217 pts/0    00:00:00 ps
3218 pts/0    00:00:00 ps
3219 pts/0    00:00:00 ps
3221 pts/0    00:00:00 ps
3223 pts/0    00:00:00 ps

As for Windows, the termination is based on the process handle instead of the PID, so I assume that means Windows is safe in this regard. There was a prior discussion about this actually:
https://bugs.python.org/issue36067#msg336243
Getting process creation time is relatively easy, even though platform-dependent (and should be done in C).
pidfd API would be nicer to use, but it seems it's not portable and relatively recent.
History
Date User Action Args
2019-11-14 03:19:22giampaolo.rodolasetrecipients: + giampaolo.rodola, vstinner, njs
2019-11-14 03:19:22giampaolo.rodolasetmessageid: <1573701562.46.0.241782603067.issue38630@roundup.psfhosted.org>
2019-11-14 03:19:22giampaolo.rodolalinkissue38630 messages
2019-11-14 03:19:21giampaolo.rodolacreate