On 15/06/11 04:27, Michael Dale wrote:
> For the TimedMediaHandler I was adding more fine grain control over
> background processes [1] and ran into a unix issue around getting both a
> pid and exit status for a given background shell command.
> 
> Essentially with a background task I can get the pid or the exit status
> but can't seem to get both:
> 
> to get the pid:
> $pid = wfShellExec("nohup nice -n 19 $cmd > /tmp/stdout.log & echo $!";
> 
> put the exit status into a file:
> $pid = wfShellExec("nohup nice -n 19 $cmd > /tmp/stdout.log && echo $? >
> /tmp/exit.status";
> 
> But if I try to get both either my exit status is for the "echo pid"
> command or my pid is for the "echo exit status" command. It seems like
> there should be some shell trick back-reference background tasks or
> something

Maybe something like:

#!/bin/bash
trap 'kill %1' SIGINT SIGTERM

(
   $cmd > /tmp/stdout.log
   echo $? > /tmp/exit.status
) &

subshell="$!"
cmdpid=

# Wait for the command to start
for i in `seq 100`;do
   cmdpid=`ps --ppid "$subshell" -o pid --no-headers`
   if [ -n "$cmdpid" ]; then
      break
  fi
  sleep 0.1
done

# Return the PID to MediaWiki
echo "$cmdpid"


There comes a point with every shell script project where you realise
it would have been easier to use a real programming language from the
start. In this case, doing it in PHP with pcntl_fork(), pcntl_exec()
and pcntl_wait() would be a reasonable solution. In my experience, you
can't ask the question "how do I do X in shell script" and expect to
like the answer.

-- Tim Starling


_______________________________________________
Wikitech-l mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/wikitech-l

Reply via email to