blob: 51e6c58e1e67c129302079080dc837a2d56da14b [file] [log] [blame]
Guido van Rossumf7221c32000-02-25 19:25:05 +00001"""This test checks for correct fork() behavior.
2
3We want fork1() semantics -- only the forking thread survives in the
4child after a fork().
5
6On some systems (e.g. Solaris without posix threads) we find that all
7active threads survive in the child after a fork(); this is an error.
8
Moshe Zadkafc3fc332001-01-30 18:35:32 +00009While BeOS doesn't officially support fork and native threading in
10the same application, the present example should work just fine. DC
Guido van Rossumf7221c32000-02-25 19:25:05 +000011"""
12
13import os, sys, time, thread
Marc-André Lemburg36619082001-01-17 19:11:13 +000014from test_support import verify, verbose, TestSkipped
Guido van Rossumf7221c32000-02-25 19:25:05 +000015
Guido van Rossum49517822000-05-04 00:36:42 +000016try:
17 os.fork
18except AttributeError:
Thomas Woutersb9fa0a82000-08-04 13:34:43 +000019 raise TestSkipped, "os.fork not defined -- skipping test_fork1"
Guido van Rossum49517822000-05-04 00:36:42 +000020
Guido van Rossumf7221c32000-02-25 19:25:05 +000021LONGSLEEP = 2
22
23SHORTSLEEP = 0.5
24
Fred Drake1a4b5932000-04-10 15:36:39 +000025NUM_THREADS = 4
26
Guido van Rossumf7221c32000-02-25 19:25:05 +000027alive = {}
28
Guido van Rossumc1488412000-04-24 14:07:03 +000029stop = 0
30
Guido van Rossumf7221c32000-02-25 19:25:05 +000031def f(id):
Guido van Rossumc1488412000-04-24 14:07:03 +000032 while not stop:
Guido van Rossumf7221c32000-02-25 19:25:05 +000033 alive[id] = os.getpid()
34 try:
35 time.sleep(SHORTSLEEP)
36 except IOError:
37 pass
38
39def main():
Fred Drake1a4b5932000-04-10 15:36:39 +000040 for i in range(NUM_THREADS):
Guido van Rossumf7221c32000-02-25 19:25:05 +000041 thread.start_new(f, (i,))
42
43 time.sleep(LONGSLEEP)
44
45 a = alive.keys()
46 a.sort()
Marc-André Lemburg36619082001-01-17 19:11:13 +000047 verify(a == range(NUM_THREADS))
Fred Drake1a4b5932000-04-10 15:36:39 +000048
49 prefork_lives = alive.copy()
Guido van Rossumf7221c32000-02-25 19:25:05 +000050
Guido van Rossum2242f2f2001-04-11 20:58:20 +000051 if sys.platform in ['unixware7']:
52 cpid = os.fork1()
53 else:
54 cpid = os.fork()
Guido van Rossumf7221c32000-02-25 19:25:05 +000055
56 if cpid == 0:
57 # Child
58 time.sleep(LONGSLEEP)
59 n = 0
Guido van Rossumf7221c32000-02-25 19:25:05 +000060 for key in alive.keys():
Fred Drake1a4b5932000-04-10 15:36:39 +000061 if alive[key] != prefork_lives[key]:
Guido van Rossumf7221c32000-02-25 19:25:05 +000062 n = n+1
63 os._exit(n)
64 else:
65 # Parent
66 spid, status = os.waitpid(cpid, 0)
Marc-André Lemburg36619082001-01-17 19:11:13 +000067 verify(spid == cpid)
68 verify(status == 0,
69 "cause = %d, exit = %d" % (status&0xff, status>>8) )
Guido van Rossumc1488412000-04-24 14:07:03 +000070 global stop
71 # Tell threads to die
72 stop = 1
73 time.sleep(2*SHORTSLEEP) # Wait for threads to die
Guido van Rossumf7221c32000-02-25 19:25:05 +000074
75main()