Merge branch '8784-dir-listings'
[arvados.git] / crunch_scripts / arvados_ipc.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 import os
6 import re
7 import sys
8 import subprocess
9
10 def pipe_setup(pipes, name):
11     pipes[name,'r'], pipes[name,'w'] = os.pipe()
12
13 def pipe_closeallbut(pipes, *keepus):
14     for n,m in pipes.keys():
15         if (n,m) not in keepus:
16             os.close(pipes.pop((n,m), None))
17
18 def named_fork(children, name):
19     children[name] = os.fork()
20     return children[name]
21
22 def waitpid_and_check_children(children):
23     """
24     Given a dict of childname->pid, wait for each child process to
25     finish, and report non-zero exit status on stderr. Return True if
26     all children exited 0.
27     """
28     all_ok = True
29     for (childname, pid) in children.items():
30         # all_ok must be on RHS here -- we need to call waitpid() on
31         # every child, even if all_ok is already False.
32         all_ok = waitpid_and_check_exit(pid, childname) and all_ok
33     return all_ok
34
35 def waitpid_and_check_exit(pid, childname=''):
36     """
37     Wait for a child process to finish. If it exits non-zero, report
38     exit status on stderr (mentioning the given childname) and return
39     False. If it exits zero, return True.
40     """
41     _, childstatus = os.waitpid(pid, 0)
42     exitvalue = childstatus >> 8
43     signal = childstatus & 127
44     dumpedcore = childstatus & 128
45     if childstatus != 0:
46         sys.stderr.write("%s child %d failed: exit %d signal %d core %s\n"
47                          % (childname, pid, exitvalue, signal,
48                             ('y' if dumpedcore else 'n')))
49         return False
50     return True
51