How to create a new background process in a KSH "while read" loop?

Posted by yael on Super User See other posts from Super User or by yael
Published on 2010-06-20T13:42:19Z Indexed on 2010/12/27 3:56 UTC
Read the original article Hit count: 270

Filed under:
|

The following test script has a problem. When I add the line (sleep 5 ) & in the script then the "while read" loop does not read all lines from the file, but only prints the first line.

But when I remove the ( sleep 5 ) & from the script, then the script prints all lines as defined in the file.

Why the ( sleep 5 ) & causes this?

And how to solve the problem? I want to create a new process (for which the sleep is just an example) in the while loop:

$ more test 
#!/bin/ksh  
while read -r line ; do
    echo Read a line:
    echo $line

    ( sleep 5 )&
    RESULT=$!
    echo Started background sleep with process id $RESULT

    sleep 1
    echo Slept for a second

    kill $RESULT 
    echo Killed background sleep with process id $RESULT
done < file
echo Completed 

On my Linux, when using the following contents of file:

$ more file 
123 aaa 
234 bbb 
556 ccc

...running ./test just gives me:

Read a line:
123 aaa
Started background sleep with process id 4181
Slept for a second 
Killed background sleep with process id 4181
Completed

© Super User or respective owner

Related posts about linux

Related posts about ksh