Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

obtaining pid of child process

Tags:

I am using python's multiprocessing module to spawn new process

as follows :

import multiprocessing
import os
d = multiprocessing.Process(target=os.system,args=('iostat 2 > a.txt',))
d.start()

I want to obtain pid of iostat command or the command executed using multiprocessing module

When I execute :

 d.pid 

it gives me pid of subshell in which this command is running .

Any help will be valuable .

Thanks in advance

like image 763
tazim Avatar asked Jul 26 '10 03:07

tazim


People also ask

How do parents get PID in child process?

Type the simply “pstree” command with the “-p” option in the terminal to check how it displays all running parent processes along with their child processes and respective PIDs. It shows the parent ID along with the child processes IDs.

How do I test my child for PID in Linux?

We can find the PIDs of the child processes of a parent process in the children files located in the /proc/[pid]/task/[tid] directories.

Which function is used to get the PID of a process?

You can get the process ID of a process by calling getpid . The function getppid returns the process ID of the parent of the current process (this is also known as the parent process ID).

Does parent process wait for child?

If any process has more than one child processes, then after calling wait(), parent process has to be in wait state if no child terminates. If only one child process is terminated, then return a wait() returns process ID of the terminated child process.


2 Answers

Similar to @rakslice, you can use psutil:

import signal, psutil
def kill_child_processes(parent_pid, sig=signal.SIGTERM):
    try:
      parent = psutil.Process(parent_pid)
    except psutil.NoSuchProcess:
      return
    children = parent.children(recursive=True)
    for process in children:
      process.send_signal(sig)
like image 54
zhanxw Avatar answered Sep 19 '22 15:09

zhanxw


Since you appear to be using Unix, you can use a quick ps command to get the details of the child processes, like I did here (this is Linux-specific):

import subprocess, os, signal

def kill_child_processes(parent_pid, sig=signal.SIGTERM):
        ps_command = subprocess.Popen("ps -o pid --ppid %d --noheaders" % parent_pid, shell=True, stdout=subprocess.PIPE)
        ps_output = ps_command.stdout.read()
        retcode = ps_command.wait()
        assert retcode == 0, "ps command returned %d" % retcode
        for pid_str in ps_output.split("\n")[:-1]:
                os.kill(int(pid_str), sig)
like image 32
rakslice Avatar answered Sep 23 '22 15:09

rakslice