help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Help-bash] Unexpected behaviour in job control inside subshell environm


From: Diego Augusto Molina
Subject: [Help-bash] Unexpected behaviour in job control inside subshell environment
Date: Thu, 1 Dec 2016 12:55:04 -0300
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.4.0

Hi, I was looking for a way to test if the "sleep" command could be coerced in some way to tell if the given arguments would be ok. The thing is I want to test if an argument received by a function is of a suitable format for that command. Different "sleep" implementations accept different forms of arguments so I wanted to make sleep command tell me if the argument is ok. So I came up with the following idea:

SLEEP_ARG=wrong-value;
(
  sleep "10${SLEEP_ARG}" &
  sleep 0.1; # Optional but recommended
  jobs -r 1;
  if [ $? -eq 0 ]; then
    kill -9 $!;
    exit 0;
  else
    exit 1;
  fi;
) &> /dev/null;

The hypothesis is that any acceptable argument for "sleep" that represents the time to sleep could have prepended any other number to make sure it's a big enough time to test if it's running in background or if it has exited immediately. So, if the argument is right then it will sleep in background and "jobs -r 1" will exit successfully, which would cause the first branch of the "if" statement to kill the background process and exit the subshell successfully. If the argument is wrong then "sleep" will exit immediately and "jobs -r 1" will exit unsuccessfully, causing the second branch of the "if" statement to take control and exit the subshell unsuccessfully. The optional but recommended "sleep 0.1" ensures the first "sleep" command has the time to exit unsuccessfully before bash delivers control to the "jobs -r 1" statement after forking the first "sleep" to background. The downside is that I'm already assuming that "sleep" can receive decimal values. Note that all stdout and stderr of the subshell will be lost completely since all I need is to know if the argument is correct or not.

But the effect is odd: the subshell always returns successfully and I can verify that "jobs -r 1" detects the first "sleep" as running even when it isn't. Proof of concept:

SLEEP_ARG=wrong-value;
(
  sleep "10${SLEEP_ARG}";
  sleep 3; # Obscenely high
  jobs -r 1;
  echo "Exit status: $?";
);

Whether or not all this is of any use (or just overthinking utterly simple things) is not as important as the fact that (I guess) it should work. I'm probably settling for somthing simpler like assuming that the argument should conform to some regexp.

Cheers.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]