using python i am executing this proc = subprocess.Popen(
[f"{bin_home}/bin/myBin"],
cwd="/",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) after execution I need to get pid but not pid of proc but accuall pid of myBin in unix system
Assistant
User
using python i am executing this proc = subprocess.Popen(
[f"{bin_home}/bin/myBin &"],
cwd="/",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) i am detuching from process so pid should be in stdout I need this pid
Assistant
When you run a command in Unix-like systems with an & at the end, it typically means you want to start the process in the background. In this case, the command you provided will start as a background job, and it will output the PID of that job to the stdout of the shell.
User
in python I want to execute following shell command '/opt/myBin/mybin &'
Assistant
When you use subprocess.Popen to start a process in Python, the process you start (in this case, myBin) runs as a child of the Python process and the PID returned by the Popen object (proc.pid) refers to the subprocess.Popen instance itself, not the PID of the child process (myBin) that it is running.
To get the actual PID of the child process myBin, you can do the following:
Use the preexec_fn argument in subprocess.Popen. This allows you to retrieve the PID of the child process right after it is created.
Set the Popen instance to not use stdout or stderr just for capturing the PID, or handle output accordingly.
Here is a way to get the PID of the child process myBin using a small function to wrap the Popen call:
python
import subprocess
import os
import time
def start_process_and_get_child_pid(bin_home):
# Start the process
proc = subprocess.Popen(
[f"{bin_home}/bin/myBin"],
cwd="/",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
preexec_fn=os.setsid # Optional: Creates a new session
)
# Wait for a little to allow the child process to fully initiate
time.sleep(0.1)
# Use `ps` command to find the actual PID of the binary
# Assuming you have just this one instance running,
# you could use `pgrep` with `-P` (parent PID) to find the child.
# Since we might not have unique identifiers on Linux,
# use 'pstree' if necessary to track the hierarchy.
# Get the child PID from the Popen process' group id (if using setsid)
child_pid = os.getpgid(proc.pid)
return child_pid
# Usage
bin_home = "/path/to/your/bin"
child_pid = start_process_and_get_child_pid(bin_home)
print(f"Child PID of myBin: {child_pid}")
Note:
Ensure that your myBin is running long enough to avoid race conditions where the main Python process continues before myBin is fully initialized.
In most cases, the above method of using os.getpgid for the child process might not always capture the direct PID of the binary, and you may need to use other means to determine the specific PID of the process, like using pgrep or similar system commands to filter out PIDs based on arguments or process names.
The preexec_fn=os.setsid prepares the child process to run in a new session. Depending on how your application's processes are managed, you might want to adjust how you retrieve the PID accordingly.
Alternative approach:
If you need the PID right after starting the process, another way can be implemented using the os.waitpid after launching myBin in a way to directly capture it:
However, the simplest and most straightforward way involves waiting for a correct output for the process identifier. You may need to customize it based on how myBin works and returns values in your system.
myBin
However, if you run subprocess.Popen with the command string directly containing &, it may not behave as you expect because subprocess.Popen does not invoke a shell by default unless you specify it. To achieve this, you can either invoke the shell explicitly, or you can capture the PID from the output in another manner.
Here’s how you can correctly execute a background process and capture its PID using a shell invocation:
python
import subprocess
import re
def start_background_process(bin_home):
# Command to start the process in the background
command = f"{bin_home}/bin/myBin & echo $!"
# Start the process using a shell
proc = subprocess.Popen(
command,
cwd="/",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True, # Use shell to execute the command
text=True, # Get output as text instead of bytes
)
# Capture the output and error
stdout, stderr = proc.communicate()
# Handle the output to find the PID
# The last echoed result should be the PID; output would be like "12345"
pid = stdout.strip() # Get the PID from stdout
if stderr:
print(f"Error: {stderr.strip()}")
return pid
# Usage
bin_home = "/path/to/your/bin"
pid = start_background_process(bin_home)
print(f"Child PID of myBin: {pid}")
Explanation:
Command: The command to execute is myBin & echo $!. This runs myBin in the background and immediately echoes the PID of the last background job, which is the PID of myBin.
Shell=True: This tells Python to execute the command through the shell, which allows the use of shell-specific features such as &.
stdout and stderr: Using communicate() captures both the standard output and standard error of the command.
Extracting the PID: We use strip() to clean up the output and get just the PID.
Important Notes:
It’s crucial to ensure that myBin behaves correctly in the background. If it terminates immediately, you might receive a non-useful PID.
Always handle errors and exceptions for robust code in production environments.
In Python, if you want to run the command /opt/myBin/mybin & to execute mybin in the background and capture its PID, you'll generally want to use a shell invocation. This approach allows you to utilize shell features like background execution.
Since you’ve specifically mentioned to run the command in the background with the &, here's how you can do that using subprocess.Popen with shell=True:
Example Code:
python
import subprocess
def run_background_process():
command = '/opt/myBin/mybin & echo $!' # Run the command and echo the PID
# Start the subprocess using the shell
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True, # Invoke the shell
text=True # Get output as text
)
# Capture the output and errors
stdout, stderr = proc.communicate()
# Extract the PID from stdout
pid = stdout.strip() # Remove any surrounding whitespace
if stderr:
print(f"Error: {stderr.strip()}")
return pid
# Usage
pid = run_background_process()
print(f"Child PID of mybin: {pid}")
Explanation:
Command: The command executed is /opt/myBin/mybin & echo $!. The & places mybin in the background, and echo $! prints the PID of the most recently executed background process (which is mybin in this case).
Popen:
shell=True: This indicates that the command should be run through the shell, which evaluates the & and executes it accordingly.
stdout=subprocess.PIPE: Captures the standard output from the command.
stderr=subprocess.PIPE: Captures any errors that occur when running the command.
text=True: This means that Python returns the output as a string rather than bytes, which is more convenient for text processing.
Output Extraction: proc.communicate() retrieves the output and errors. After that, stdout.strip() is used to clean any extra whitespace around the PID.
Important Considerations:
Immediate Execution: The above command will immediately return the PID for mybin, but you must ensure that mybin is designed to run properly in the background. If it terminates quickly, you might get a PID that doesn't correspond to a running process.
Error Handling: Always check stderr for any errors that might occur when attempting to run the command.
Security Note: Be cautious with shell=True, as it can introduce security risks if you're dealing with user input unless that input is sanitized.