0

I have started my process in background and I would like to kill that process using a C program using popen().

I have tried in many ways but in vain. The reason is when I run a C code, it is executed in a sub-shell because of which I can't get the processes running in main shell.

I used $! to get the latest pid running in the background, but because of the above reason it didn't work.

Sobhan
  • 21
  • 1
  • 10

3 Answers3

1
my_process & pids="${pids-} $!" //start my process
sleep 10                       // run for 10 seconds
kill -2 $pids                  //kill the process

Also you can store PID in file and kill it.like

./process1.sh &
echo $! > /tmp/process1.pid

kill -9 `cat /tmp/process*.pid`
rm /tmp/process*.pid
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
  • Thanks for your answer but I'm afraid, I have to make a solution without redirecting it to a temporary file Also,could you please elaborate on the statement "my_process & pids="${pids-} $!"" – Sobhan Jul 01 '14 at 13:15
  • @Sobhan The `${pids-}` syntax is to avoid errors when using `set -o nounset`. – Jayesh Bhoi Jul 02 '14 at 03:55
  • Unfortunately, the possiblity of killing the background process from shell script is now ruled out. I have to kill it by executing unix commands from C either by using 'popen' or 'system()'. As running unix commands from C will again run in a subshell, could you make the way out to achieve this.. – Sobhan Jul 02 '14 at 06:03
  • @Sobhan yes it's not possible to kill process using `system` or `popen` command but you can do. see [here](http://stackoverflow.com/questions/4435942/how-to-kill-background-process-from-system-function-call) and [here](http://stackoverflow.com/questions/10985544/using-c-to-send-an-exec-process-to-the-background) – Jayesh Bhoi Jul 02 '14 at 06:27
  • The first link you have given starts the background process in C itself and kills it over there. But, in my case the bg process starts in mail shell and I have to kill it in sub-shell(C program). So,if there is any way to kill such process please post here.. – Sobhan Jul 02 '14 at 08:14
1

You should make your process into a daemon, that way you can start, end and restart it without complications.

You can start here: Best way to make a shell script daemon?

Community
  • 1
  • 1
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
0

+1 on Raydel's answer

Another alternative (since there are so many ways to do things) If you have root you can also create it as a service and then start it and stop it manually using the "service" commands.

(Sorry wanted to add as a comment to Raydel's but my rep is not high enough apparently so adding as a separate answer)

ben
  • 111
  • 4