Why pkill -f Fails on Complex Process Trees
You are likely encountering a classic case of "process hiding" caused by shell quoting and argument parsing, rather than a bug in pkill. When you run ps ax | grep 'string', you see three processes. When you run pkill -f 'string', they remain alive. The discrepancy lies in how the arguments are constructed versus how the matching tool scans them.
The core issue is that your target processes are wrapped inside a shell wrapper: sh -c. This wrapper, combined with sudo and the screen utility, creates a multi-layered process tree where the actual command line arguments are obscured or modified by the parent shells.
In your specific example, the first process (PID 342) is a sh -c instance. It parses the input string and executes the subsequent commands. The arguments visible in ps ax often include quotes that were part of the original shell invocation. However, when you pass a pattern to pkill -f, it scans the full command line of the process as stored by the kernel. If the process list shows quoted strings (e.g., "http://zoink.it/torrent/...") but your kill command passes an unquoted string or one that doesn't exactly match the internal representation, the match fails.
More critically, pkill matches against the entire command line. In your ps output, you see multiple layers of invocation:
sh -c sudo screen ...sudo screen /usr/bin/python ...screen /usr/bin/python ...
If you try to match a substring like the torrent URL, pkill usually works fine unless the process list is displaying escaped quotes or if the pattern requires exact string matching versus globbing. However, the most common failure point here is that ps ax truncates arguments or displays them differently depending on the system's version of GNU coreutils or procps.
The Real Culprit: Process Hierarchy and sudo
The primary reason your kill command seems to fail is often the presence of sudo and sh -c.
- PID 342 is a shell spawned by the user.
- PID 343 is likely the result of that shell executing
sudo screen .... - PID 344 might be a child of the sudo process or directly running under a different context depending on how
sudowas invoked withscreen.
When you use ps ax, you see all processes. But pkill -f searches for the pattern in the full command line of all children. If the pattern includes quotes (e.g., "torrent.url"), but the kernel stores the argument without them (or vice versa depending on how ps renders it), the match fails.
However, there is a more aggressive approach that bypasses these matching ambiguities entirely: using killall with precise process names or targeting the specific PID group if they are related. But the most robust solution for "hiding" processes like this is to target the actual executable name rather than the arguments, provided you know the binary is unique enough.
Implementing a Kill Command in PHP
If you need to automate this via PHP (as requested), you cannot simply pipe ps output directly into a kill command within a standard PHP script due to shell injection risks and return value handling. Instead, you should use proc_open or popen to execute the system command safely.
Here is how you can construct the logic to find and kill processes containing a specific string (like the filename Momomoko.E01...) using PHP:
<?php
$targetString = 'Momomoko.E01.140011.HDTV.H264.720p.mp4';
// Use pkill directly with the -f flag to search command lines.
// We pass the string unquoted inside the shell command to ensure it matches
// the pattern regardless of internal quoting in the ps output.
$command = "pkill -9 -f '{$targetString}'";
// Execute via proc_open to handle potential output or errors if necessary
$descriptorSpec = [
0 => ['pipe', 'read'], // stdin (usually not needed for pkill)
1 => ['pipe', 'write'], // stdout
2 => ['pipe', 'write'] // stderr
];
$process = proc_open($command, $descriptorSpec, $pipes);
if ($process !== false) {
// Close the pipes to allow the process to terminate immediately
foreach ($pipes as $pipe) {
fclose($pipe);
}
$status = proc_close($process);
if ($status === 0) {
echo "Processes killed successfully.\n";
} else {
echo "Error killing processes. Status: {$status}\n";
// Check exit code details if needed (e.g., 137 for SIGKILL)
}
} else {
echo "Failed to execute command or no matches found.\n";
}
?>
Why -9 Matters and When to Use It
You asked about kill -9. The -9 flag sends SIGKILL, which forces an immediate termination. This is necessary when a process ignores standard signals like SIGTERM (sent by default pkill or kill).
- Trade-off:
SIGKILLdoes not give the application a chance to clean up resources, flush buffers, or save state. For a BitTorrent client (likebtdownloadcurses), this means the connection drops instantly, and any partially downloaded data might be orphaned or require re-seeding before download resumes. - Alternative: If you can afford a brief delay, omit
-9. Let the application handle its own shutdown sequence. This prevents corruption of the torrent state file and ensures the client stops seeding gracefully.
Debugging the Match Failure
If pkill -f still fails after ensuring your string is correct, inspect the exact command line using ps -o pid,comm,args -p <PID>. You will often find that ps ax hides quotes or truncates long arguments in a way that differs from what pkill reads from /proc/<pid>/cmdline.
In cases where process names are obfuscated by shells (like sh -c), the most reliable method is to match the specific executable, such as /usr/bin/btdownloadcurses. If you know the binary path and want to kill all instances running it:
pkill -9 /usr/bin/btdownloadcurses
This bypasses argument matching issues entirely. For complex setups involving screen or sudo, ensure you are targeting the actual work process (the one running the Python script) rather than the shell wrapper, as killing the wrapper might not kill the screen session's child processes if they have detached.
For further details on managing such processes in a production environment, consider looking into orchestration tools that handle signal propagation correctly. If you are building a solution around Laravel or need to manage background jobs within that ecosystem, ensure your queue workers do not spawn these types of shell-wrapped processes without supervision, as they can become hard to terminate.