|
12 | 12 | import StringIO
|
13 | 13 | import re
|
14 | 14 | import socket
|
| 15 | +import tempfile |
| 16 | +try: |
| 17 | + import psutil |
| 18 | + psutil_imported = True |
| 19 | +except ImportError: |
| 20 | + psutil_imported = False |
15 | 21 |
|
16 | 22 | import gen_print as gp
|
17 | 23 | import gen_cmd as gc
|
@@ -401,3 +407,57 @@ def to_signed(number,
|
401 | 407 | return ((2**bit_width) - number) * -1
|
402 | 408 | else:
|
403 | 409 | return number
|
| 410 | + |
| 411 | + |
| 412 | +def get_child_pids(quiet=1): |
| 413 | + |
| 414 | + r""" |
| 415 | + Get and return a list of pids representing all first-generation processes |
| 416 | + that are the children of the current process. |
| 417 | +
|
| 418 | + Example: |
| 419 | +
|
| 420 | + children = get_child_pids() |
| 421 | + print_var(children) |
| 422 | +
|
| 423 | + Output: |
| 424 | + children: |
| 425 | + children[0]: 9123 |
| 426 | +
|
| 427 | + Description of argument(s): |
| 428 | + quiet Display output to stdout detailing how |
| 429 | + this child pids are obtained. |
| 430 | + """ |
| 431 | + |
| 432 | + if psutil_imported: |
| 433 | + # If "import psutil" worked, find child pids using psutil. |
| 434 | + current_process = psutil.Process() |
| 435 | + return [x.pid for x in current_process.children(recursive=False)] |
| 436 | + else: |
| 437 | + # Otherwise, find child pids using shell commands. |
| 438 | + print_output = not quiet |
| 439 | + |
| 440 | + ps_cmd_buf = "ps --no-headers --ppid " + str(os.getpid()) +\ |
| 441 | + " -o pid,args" |
| 442 | + # Route the output of ps to a temporary file for later grepping. |
| 443 | + # Avoid using " | grep" in the ps command string because it creates |
| 444 | + # yet another process which is of no interest to the caller. |
| 445 | + temp = tempfile.NamedTemporaryFile() |
| 446 | + temp_file_path = temp.name |
| 447 | + gc.shell_cmd(ps_cmd_buf + " > " + temp_file_path, |
| 448 | + print_output=print_output) |
| 449 | + # Sample contents of the temporary file: |
| 450 | + # 30703 sleep 2 |
| 451 | + # 30795 /bin/bash -c ps --no-headers --ppid 30672 -o pid,args > |
| 452 | + # /tmp/tmpqqorWY |
| 453 | + # Use egrep to exclude the "ps" process itself from the results |
| 454 | + # collected with the prior shell_cmd invocation. Only the other |
| 455 | + # children are of interest to the caller. Use cut on the grep results |
| 456 | + # to obtain only the pid column. |
| 457 | + rc, output = \ |
| 458 | + gc.shell_cmd("egrep -v '" + re.escape(ps_cmd_buf) + "' " |
| 459 | + + temp_file_path + " | cut -c1-5", |
| 460 | + print_output=print_output) |
| 461 | + # Split the output buffer by line into a list. Strip each element of |
| 462 | + # extra spaces and convert each element to an integer. |
| 463 | + return map(int, map(str.strip, filter(None, output.split("\n")))) |
0 commit comments