-   Programming (
-   -   How to use Shell script to kill an on going program? (

cruiz_bugs 08-03-2009 11:28 AM

How to use Shell script to kill an on going program?
Hi, I'm still newbie in linux and i'm trying to run a shell script to listen to a GPS receiver port.
So in my script, I have

cat /dev/ttyS2 > outputFile.txt
which will write the all the data to outputFile.txt.

This is like executing a while(1) loop,it will always listen and write to outputFile forever.
However, i want to stop this after it runs for 1 or 2 minute.
manually, i can use ctrl-c to stop it,
but now i have to make it automatic stopped.
So i was thinking to call another script (script2) to get the PID of this program and then use "kill $PID" to stop it.

but the problem is, once i execute this $cat /dev/ttyS2, the CPU will just stuck there.
it wont release the CPU to run the other script.
and I cant run script2 first because when this cat command have not been started, there is no PID for me to get.

Is there anyone knows how to solve this problem ? i try to test and simulate this using this script:


echo "_______________Shell_1 file testing_____________"
gcc -o whileLoop c_test.c
echo "starting while loop:"

this is the code for the c_test.c:
#include <stdio.h>

int main(){
int i=0;

//this loop act as a port listener.
printf("i : %d \n", i);

so what happen now is: I want to stop this while loop after it runs for 1 or 2 minute.
i know i can use for loop or a counter to solve this simple while loop, but that is not what i'm currently working at.
my program is listening to an active port.

is there anyone can advice me on how to solve this problem? thanks.

GrapefruiTgirl 08-03-2009 11:48 AM

Some tips, based on the Bash man page:

1) putting an & symbol after your cat command will cause it to fork into the background, returning control to the shell.

2) After doing that, the bash builtin variable $! will contain the PID of the last process (the cat process) which you can use for whatever means you decide to use to kill the cat process after your desired delay.



PS - Welcome to LQ!

cruiz_bugs 08-04-2009 01:38 AM

hi, thanks for the reply :)

anyway, i still dont quite get what you mean.

how to call the built in variable here?
is there any sample code that i can refers to?


catkin 08-04-2009 02:28 AM

Hello Christine :)

I understand you want to create a bash script that will run an executable for a set time. Please correct me if I am wrong.

You want something like this (not tested), based on GrapefruiTgirl's suggestion

./whileLoop &
sleep 120
kill -9 $!

It's easier to read your code when you put it in [ code ]<stuff>[ /code ] tags (without the spaces).



cruiz_bugs 08-04-2009 03:30 AM

that works.
thank you so much ^___^


pixellany 08-04-2009 08:41 AM

Moved: This thread is more suitable in <Programming> and has been moved accordingly to help your thread/question get the exposure it deserves.

All times are GMT -5. The time now is 10:02 PM.