tags:

views:

55

answers:

3
+1  A: 
User1
why are you killing a process whose output you want?
msw
The process is a hardware monitoring program that will run until it is killed. When the process receives the kill signal, it flushes its buffer. In reality, the bash script will kill my_prog when the test is over which is represented by the sleep statement above.
User1
+2  A: 

Based on your comment, I still can't see why you'd prefer killing my_prog to having it complete in an orderly fashion. Ten seconds is a pretty arbitrary measurement on a multiprocessing system whereby my_prog could generate 10k lines or 0 lines of output depending upon system load.

If you want to limit the output of my_prog to something more determinate try

my_prog | head -1000 | awk

without detaching from the shell. In the worst case, head will close its input and my_prog will get a SIGPIPE. In the best case, change my_prog so it gives you the amount of output you want.

added in response to comment:

In so far as you have control over my_prog give it an optional -s duration argument. Then somewhere in your main loop you can put the predicate:

if (duration_exceeded()) {
    exit(0);
}

where exit will in turn properly flush the output FILEs. If desperate and there is no place to put the predicate, this could be implemented using alarm(3), which I am intentionally not showing because it is bad.

The core of your trouble is that my_prog runs forever. Everything else here is a hack to get around that limitation.

msw
See my comment in my answer. I guess I could have given more detail on the original question. The solution above might work for some, but this case is a bit different. Thank you for all your help so far. I hope you can tell me of an easier solution than my answer.
User1
+2  A: 

Add a shell wrapper around your command and capture the pid. For my example I use iostat.

#!/bin/sh
echo $$ > /tmp/my.pid
exec iostat 1

Exec replaces the shell with the new process preserving the pid.

test.sh | grep avg

While that runs:

$ cat my.pid 
22754
$ ps -ef | grep iostat
userid  22754  4058  0 12:33 pts/12   00:00:00 iostat 1

So you can:

sleep 10
kill `cat my.pid`

Is that more elegant?

Demosthenex
+1, Wrapper. This is really an essence of UNIX design.
Anders