Read lines from command and kill the process

I would like to do the following:

  1. Start an external command
  2. Read lines from the command
  3. If the line contains a certain text, kill the external command
  4. Return once all lines are read

Is there a simple way to achieve this? The best I have come up with is this:

function getoutput()
  write("tmp.txt","line 1\nline 2\nline 3")
  out = PipeBuffer()
  process = run(pipeline(`cat tmp.txt`,out),wait=false)
  lines = String[]
  lookfordata = true
  while lookfordata
    l = readline(out)
    isempty(l) || push!(lines,l)
    occursin("2",l) && (kill(process); break)
    sleep(0.001) # helper line, without which the while never returns
    lookfordata = !eof(out) || process_running(process)
lines = getoutput()

Note in particular the “helper line” sleep(0.001). Without this, or another “helper line”, the while loop never returns. Another helper line that does the trick is a print statement, e.g. println("Hello!"). This is puzzling to me…

I have tried using eachline(`cat tmp.txt`) in a for-loop:

for l in eachline(`cat tmp.txt`)
  occursin("2",l) && break

This is much more compact. However, now the break does not kill the process, so it does not meet my requirements.

I am using Julia 1.1. I am happy to hear any thoughts!