I would like to spawn a process suspended, possibly in the context of another user (e.g. via sudo -u ...), set up some iptables rules for the spawned process, continue running the process, and remove the iptable rules when the process exists.
Is there any standart means (bash, corutils, etc.) that allows me to achieve the above? In particular, how can I spawn a process in a suspended state and get its pid?
You can (usually) tell Unix to suspend the job that is currently connected to your terminal by typing Control-Z (hold the control key down, and type the letter z). The shell will inform you that the process has been suspended, and it will assign the suspended job a job ID.
Killing a background process is fairly straightforward; use the command pkill and the process ID, or process name as: Using the pkill command will force terminate (-9) the processes with the process name of ping.
Simply find the process in the list that you'd like to suspend, right-click, and choose Suspend from the menu. Once you've done so, you'll notice that the process shows up as suspended, and will be highlighted in dark gray.
While in a command line such as Linux, and Unix, Ctrl + Z is used to send a TSTP signal to request it to stop temporarily.
Write a wrapper script start-stopped.sh
like this:
#!/bin/sh
kill -STOP $$ # suspend myself
# ... until I receive SIGCONT
exec $@ # exec argument list
And then call it like:
sudo -u $SOME_USER start-stopped.sh mycommand & # start mycommand in stopped state
MYCOMMAND_PID=$!
setup_iptables $MYCOMMAND_PID # use its PID to setup iptables
sudo -u $SOME_USER kill -CONT $MYCOMMAND_PID # make mycommand continue
wait $MYCOMMAND_PID # wait for its termination
MYCOMMAND_EXIT_STATUS=$?
teardown_iptables # remove iptables rules
report $MYCOMMAND_EXIT_STATUS # report errors, if necessary
All this is overkill, however. You don't need to spawn your process in a suspended state to get the job done. Just make a wrapper script setup_iptables_and_start
:
#!/bin/sh
setup_iptables $$ # use my own PID to setup iptables
exec sudo -u $SOME_USER $@ # exec'ed command will have same PID
And then call it like
setup_iptables_and_start mycommand || report errors
teardown_iptables
You can write a C wrapper for your program that will do something like this :
fork
and print child pid.exec
or system
.Will this work?
Edit: Actually you can do above procedure with a shell script. Try following bash script:
#!/bin/bash
echo "Pid is $$"
echo -n "Press Enter.."
read
exec $@
You can run this as /bin/bash ./run.sh <your command>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With