4

I have a task that runs written in Mono, however sometimes (randomly) the Mono runtime will hang after the task is complete and just print:

_wapi_handle_ref: Attempting to ref unused handle 0x2828
_wapi_handle_unref_full: Attempting to unref unused handle 0x2828
_wapi_handle_ref: Attempting to ref unused handle 0x2828
_wapi_handle_unref_full: Attempting to unref unused handle 0x2828
...

to stderr forever. Is there a way of parsing stderr and killing the task when a certain pattern is matched?

A timeout is out of the question because the task can legitimately take upwards of an hour to complete normally, but if there is no work to be done will exit instantly (or at least it's supposed to).

Anthon
  • 78,313
  • 42
  • 165
  • 222
Ivan Neeson
  • 143
  • 3

1 Answers1

3
{ 
  my-mono-app 2>&1 >&3 3>&1 | awk '
    {print}
    /ref unused/ {print "Exiting."; exit(1)}' >&2
} 3>&1

awk would exit as soon as it reads one of those messages, causing my-mono-app to be killed by a SIGPIPE the next time it tries to write something on stderr.

Don't use mawk there which buffers stdin in a stupid way (or use -W interactive there).

If the application doesn't die on SIGPIPE, you'll have to kill it in some way.

One way could be:

{ sh -c 'echo "$$" >&2; exec my-mono-app' 2>&1 >&3 3>&1 | awk '
  NR == 1 {pid = $0; next}
  {print}
  /ref unused/ && ! killed {
     print "Killing",pid
     killed=1
     system("kill " pid)
  }' >&2
} 3>&1

Replace with "kill " with "kill -s KILL " if it still doesn't work.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501