Signals

Ian Littman / @iansltx

AustinPHP January 2017 / http://ian.im/sig1701

kill -9 some-bad-app

pcntl

this is for CLIs and daemons

pcntl_signal(signal, callback)

  • signal == integer signal number (use built-in constants!)
    • SIGINT (ctrl-c)
    • SIGHUP (restart)
    • SIGTERM (normal kill behavior)
    • SIGCONT, SIGUSR1, etc.
    • Nope, you can't override SIGKILL (kill -9)
  • Callback works with any callable
    • 1st arg: signal #
    • 2nd arg (PHP 7.1+): SIGINFO_T struct, as an array

NOTE

Signal handlers are one level deep

Listening for signals

  • Ticks
    • >= 4.3.0
    • Slow
  • pcntl_signal_dispatch()
    • >= 5.3.0
    • Faster, but manual
  • pcntl_async_signals(true)
    • >= 7.1.0
    • Great if you've got it!

Waiting on signals

  • OS-dependent (no OS X support)
  • Can wait with or without a timeout
    • pcntl_sigtimedwait() with timeout
    • pcntl_sigwaitinfo() without
  • Don't need to use ticks/dispatch/etc.
  • DO need to make sure callbacks are set
  • DON'T expect those callbacks to be called
  • Can wait on a set of signals (e.g. SIGCONT + SIGHUP)

Alarms are special

  • SIGALRM
  • pcntl_alarm(int)
    • Fires a SIGARLM at this process in int seconds
    • Replaces any set, pending alarm
  • If the script is sleep()ing, ends that statement early
    • Consecutive sleep() will happen normally
    • Other signals behave the same way

Putting it all together

Thanks!

Questions?