Kill Child Process and Parent Process Bash Linux

you want a set of Bash commands for managing processes in a Linux environment. Here’s an explanation of what each command does:

  1. Kill Child Process and Parent Process:

    1
    
    pid=17844 && pkill -TERM -P $pid && kill $pid

    This command first assigns the value 17844 to the variable pid. Then, it uses pkill with the -TERM option to send a termination signal to all processes with a parent process ID (PPID) equal to the value stored in pid. Finally, it uses the kill command to send a termination signal to the process with the PID stored in pid.

  2. Print PID from Command:

    1
    
    ps aux | grep "/root/bin/ssh-port-forward 45.77.47.134 12006" | grep -v grep | awk '{print $2}'

    This command lists all processes using ps aux, searches for lines containing “/root/bin/ssh-port-forward 45.77.47.134 12006” using grep, excludes the grep command itself using grep -v grep, and then uses awk to print the second column of the output, which is the PID of the matching process.

  3. Kill Child Process and Parent Process By Command:

    1
    2
    
    PC="/root/bin/ssh-port-forward 45.77.47.134 12006" &&
    PID=$(ps aux | grep "$PC" | grep -v grep | awk '{print $2}') && pkill -TERM -P $PID && kill $PID

    This command first assigns the command string “/root/bin/ssh-port-forward 45.77.47.134 12006” to the variable PC. Then, it uses a combination of commands to find the PID of the process that matches the command stored in PC, and it sends a termination signal to both the child and parent processes.

  4. Kill and Run Background Process:

    1
    2
    
    PC="/root/bin/ssh-port-forward 45.77.47.134 12006" && 
    PID=$(ps aux | grep "$PC" | grep -v grep | awk '{print $2}') && pkill -TERM -P $PID ; kill $PID ; $PC &

    This command is similar to the previous one but with an additional step. It first finds the PID of the process matching the command in PC, sends termination signals to both the child and parent processes, and then restarts the command in the background using &. This effectively stops the existing process and starts a new one in the background.

Please note that working with process management in this way can be risky, especially if you are forcefully terminating processes. Be cautious when using these commands, as they can lead to data loss or other unexpected behavior if not used carefully.

0%