blob: 03a4d6f984e5f818207bba4cb3186afef7c36af7 [file] [log] [blame]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001"""This test case provides support for checking forking and wait behavior.
2
3To test different wait behavior, overrise the wait_impl method.
4
5We want fork1() semantics -- only the forking thread survives in the
6child after a fork().
7
8On some systems (e.g. Solaris without posix threads) we find that all
9active threads survive in the child after a fork(); this is an error.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010"""
11
Georg Brandl2067bfd2008-05-25 13:05:15 +000012import os, sys, time, _thread, unittest
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013
14LONGSLEEP = 2
15SHORTSLEEP = 0.5
16NUM_THREADS = 4
17
18class ForkWait(unittest.TestCase):
19
20 def setUp(self):
21 self.alive = {}
22 self.stop = 0
23
24 def f(self, id):
25 while not self.stop:
26 self.alive[id] = os.getpid()
27 try:
28 time.sleep(SHORTSLEEP)
29 except IOError:
30 pass
31
32 def wait_impl(self, cpid):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033 for i in range(10):
34 # waitpid() shouldn't hang, but some of the buildbots seem to hang
35 # in the forking tests. This is an attempt to fix the problem.
36 spid, status = os.waitpid(cpid, os.WNOHANG)
37 if spid == cpid:
38 break
39 time.sleep(2 * SHORTSLEEP)
40
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041 self.assertEquals(spid, cpid)
42 self.assertEquals(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
43
44 def test_wait(self):
45 for i in range(NUM_THREADS):
Georg Brandl2067bfd2008-05-25 13:05:15 +000046 _thread.start_new(self.f, (i,))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000047
48 time.sleep(LONGSLEEP)
49
Guido van Rossumcc2b0162007-02-11 06:12:03 +000050 a = sorted(self.alive.keys())
Guido van Rossum805365e2007-05-07 22:24:25 +000051 self.assertEquals(a, list(range(NUM_THREADS)))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052
53 prefork_lives = self.alive.copy()
54
55 if sys.platform in ['unixware7']:
56 cpid = os.fork1()
57 else:
58 cpid = os.fork()
59
60 if cpid == 0:
61 # Child
62 time.sleep(LONGSLEEP)
63 n = 0
64 for key in self.alive:
65 if self.alive[key] != prefork_lives[key]:
66 n += 1
67 os._exit(n)
68 else:
69 # Parent
70 self.wait_impl(cpid)
71 # Tell threads to die
72 self.stop = 1
73 time.sleep(2*SHORTSLEEP) # Wait for threads to die