I have the following code
xterm -e <some command> &
<line 2 command>
You can simply get PID of the last background task lauched with $!, and then kill it after your line 2 command is achived.
xterm -e <some command> & myBackgroundXtermPID=$! <line 2 command> kill $myBackgroundXtermPID
I assume that if your background process ends before line 2 , its PID will not be reused by another process (if you run out of PID numbers).