import json, pathlib, select, subprocess, time
rows = []
children = []
try:
    for marker in ('agent7-psyche', 'agent7-other-psyche'):
        child = subprocess.Popen(['sh', '-c', 'read -r hold; : ' + marker], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        children.append(child)
        proc = pathlib.Path('/proc') / str(child.pid)
        deadline = time.monotonic() + 2
        while marker.encode() not in (proc / 'cmdline').read_bytes() and time.monotonic() < deadline:
            time.sleep(.005)
        row = {'pid':child.pid, 'exe':str((proc / 'exe').resolve()), 'cmdline':(proc / 'cmdline').read_bytes().decode().replace('\0',' ')}
        assert marker in row['cmdline'], row
        time.sleep(.2)
        assert child.poll() is None
        assert not (proc / 'task' / str(child.pid) / 'children').read_text().strip()
        rows.append(row)
    assert rows[0]['exe'] == rows[1]['exe']
    assert 'agent7-psyche' not in rows[1]['cmdline']
finally:
    for child in children:
        child.kill()
        child.wait(timeout=2)
        child.stdin.close()
        ready, _, _ = select.select([child.stdout, child.stderr], [], [], .5)
        assert len(ready) == 2
        assert child.stdout.read() == child.stderr.read() == b''
        child.stdout.close(); child.stderr.close()
        assert not (pathlib.Path('/proc') / str(child.pid)).exists()
print(json.dumps({'rows':rows,'descendants':0,'all_reaped':True,'stdout_stderr_eof':True}))
