WelcomeWelcome | FAQFAQ | DownloadsDownloads | WikiWiki

Author Topic: unexpected pgrep exit code when running non-interactively  (Read 1943 times)

Offline GNUser

  • Wiki Author
  • Hero Member
  • *****
  • Posts: 1511
unexpected pgrep exit code when running non-interactively
« on: October 08, 2019, 07:42:54 AM »
In a non-interactive shell script, foo in pgrep -f 'regex' && foo never runs.

However, foo in pgrep -f 'regex' >/dev/null && foo does run when expected.

If I try the commands in an interactive shell, foo always runs when expected.

One of the scripts I use daily is affected by this (on line 27):
https://github.com/bdantas/wifi-monitor/blob/master/wifi-monitor

The function icon_add is supposed to return immediately (without creating an icon) if an icon already exists. If I remove >/dev/null from line 27, however, the function never returns and icons pile up in the systray.

Any idea why >/dev/null is required here? I thought the exit code of a utility (pgrep in this case) should be the same regardless of where its output is going.

Offline Rich

  • Administrator
  • Hero Member
  • *****
  • Posts: 11629
Re: unexpected pgrep exit code when running non-interactively
« Reply #1 on: October 08, 2019, 08:59:54 AM »
Hi GNUser
If you add this to the shebang:
Code: [Select]
#!/bin/sh -xyou can trace the execution and maybe find a clue.

Offline GNUser

  • Wiki Author
  • Hero Member
  • *****
  • Posts: 1511
Re: unexpected pgrep exit code when running non-interactively
« Reply #2 on: October 08, 2019, 09:05:38 AM »
Thank you Rich.
I tried that and also logged the exit codes.

Interestingly, the exit codes of
Code: [Select]
pgrep -f 'regex' and
Code: [Select]
pgrep -f 'regex' >/dev/nullare different ("1 1 1 1 1 ..." in the first case, "1 0 0 0 0 ..." in the second case). The expected exit codes are the second set.

Since the exit code of a command should not depend on where its output is going, I think I found a bug in pgrep. I'll contact the developers to inquire and will report back here with what they say.

 

Offline GNUser

  • Wiki Author
  • Hero Member
  • *****
  • Posts: 1511
Re: unexpected pgrep exit code when running non-interactively [SOLVED]
« Reply #3 on: October 09, 2019, 01:15:39 PM »
I redirected the script's stderr to a log to investigate what's going on when pgrep -f 'regex' && foo fails to work as expected.

Lo and behold, a bunch of "pgrep: write error" entries show up in the log.

So it seems the issue here is that when a shell script runs in the background, pgrep gets grumpy unless its stdout is redirected somewhere (even if only to /dev/null).