:mod:`signal` --- 非同期イベントにハンドラを設定する
====================================================

.. module:: signal
   :synopsis: 非同期イベントにハンドラを設定します。


.. This module provides mechanisms to use signal handlers in Python. Some general
.. rules for working with signals and their handlers:

このモジュールでは Python でシグナルハンドラを使うための機構を提供します。
シグナルとハンドラを扱う上で一般的なルールがいくつかあります:


.. * A handler for a particular signal, once set, remains installed until it is
..   explicitly reset (Python emulates the BSD style interface regardless of the
..   underlying implementation), with the exception of the handler for
..   :const:`SIGCHLD`, which follows the underlying implementation.

* 特定のシグナルに対するハンドラが一度設定されると、明示的にリセットしないかぎり設定されたままになります (Python は背後の実装系に関係なく BSD
  形式のインタフェースをエミュレートします)。例外は :const:`SIGCHLD` のハンドラで、この場合は背後の実装系の仕様に従います。


.. * There is no way to "block" signals temporarily from critical sections (since
..   this is not supported by all Unix flavors).

* クリティカルセクションから一時的にシグナルを"ブロック"することはできません。この機能をサポートしない Unix 系システムも存在するためです。


.. * Although Python signal handlers are called asynchronously as far as the Python
..   user is concerned, they can only occur between the "atomic" instructions of the
..   Python interpreter.  This means that signals arriving during long calculations
..   implemented purely in C (such as regular expression matches on large bodies of
..   text) may be delayed for an arbitrary amount of time.

* Python のシグナルハンドラは Python のユーザが望む限り非同期で呼び出されますが、呼び出されるのは Python インタプリタの  "原子的な
  (atomic)" 命令実行単位の間です。したがって、 (巨大なサイズのテキストに対する正規表現の一致検索のような)  純粋に C
  言語のレベルで実現されている時間のかかる処理中に到着したシグナルは、不定期間遅延する可能性があります。


.. * When a signal arrives during an I/O operation, it is possible that the I/O
..   operation raises an exception after the signal handler returns. This is
..   dependent on the underlying Unix system's semantics regarding interrupted system
..   calls.

* シグナルが I/O 操作中に到着すると、シグナルハンドラが処理を返した後に I/O 操作が例外を送出する可能性があります。これは背後にある Unix
  システムが割り込みシステムコールにどういう意味付けをしているかに依存します。


.. * Because the C signal handler always returns, it makes little sense to catch
..   synchronous errors like :const:`SIGFPE` or :const:`SIGSEGV`.

* C 言語のシグナルハンドラは常に処理を返すので、 :const:`SIGFPE` や :const:`SIGSEGV`
  のような同期エラーの捕捉はほとんど意味がありません。


.. * Python installs a small number of signal handlers by default: :const:`SIGPIPE`
..   is ignored (so write errors on pipes and sockets can be reported as ordinary
..   Python exceptions) and :const:`SIGINT` is translated into a
..   :exc:`KeyboardInterrupt` exception.  All of these can be overridden.

* Python は標準でごく少数のシグナルハンドラをインストールしています: :const:`SIGPIPE` は無視されます
  (したがって、パイプやソケットに対する書き込みで生じたエラーは通常の Python 例外として報告されます) :const:`SIGINT` は
  :exc:`KeyboardInterrupt` 例外に変換されます。これらはどれも上書きすることができます。


.. * Some care must be taken if both signals and threads are used in the same
..   program.  The fundamental thing to remember in using signals and threads
..   simultaneously is: always perform :func:`signal` operations in the main thread
..   of execution.  Any thread can perform an :func:`alarm`, :func:`getsignal`,
..   :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread
..   can set a new signal handler, and the main thread will be the only one to
..   receive signals (this is enforced by the Python :mod:`signal` module, even
..   if the underlying thread implementation supports sending signals to
..   individual threads).  This means that signals can't be used as a means of
..   inter-thread communication.  Use locks instead.

* シグナルとスレッドの両方を同じプログラムで使用する場合にはいくつか注意が必要です。
  シグナルとスレッドを同時に利用する上で基本的に注意すべきことは、 :func:`signal`
  命令は常に主スレッド (main thread) の処理中で実行するということです。
  どのスレッドも :func:`alarm`\ 、 :func:`getsignal`\ 、 :func:`pause`\ 、 :func:`setitimer`\ 、 :func:`getitimer` を実行することができます。
  しかし、主スレッドだけが新たなシグナルハンドラを設定することができ、したがってシグナルを受け取ることができるのは主スレッドだけです
  (これは、背後のスレッド実装が個々のスレッドに対するシグナル送信をサポートしているかに関わらず、 Python :mod:`signal`
  モジュールが強制している仕様です)。したがって、シグナルをスレッド間通信の手段として使うことはできません。代わりにロック機構を使ってください。


.. The variables defined in the :mod:`signal` module are:

以下に :mod:`signal` モジュールで定義されている変数を示します:


.. data:: SIG_DFL

   .. This is one of two standard signal handling options; it will simply perform
   .. the default function for the signal.  For example, on most systems the
   .. default action for :const:`SIGQUIT` is to dump core and exit, while the
   .. default action for :const:`SIGCHLD` is to simply ignore it.

   二つある標準シグナル処理オプションのうちの一つです; 単純にシグナルに対する標準の関数を実行します。例えば、ほとんどのシステムでは、
   :const:`SIGQUIT` に対する標準の動作はコアダンプと終了で、 :const:`SIGCHLD` に対する標準の動作は単にシグナルの無視です。


.. data:: SIG_IGN

   .. This is another standard signal handler, which will simply ignore the given
   .. signal.

   もう一つの標準シグナル処理オプションで、受け取ったシグナルを単に無視します。


.. data:: SIG*

   .. All the signal numbers are defined symbolically.  For example, the hangup signal
   .. is defined as :const:`signal.SIGHUP`; the variable names are identical to the
   .. names used in C programs, as found in ``<signal.h>``. The Unix man page for
   .. ':cfunc:`signal`' lists the existing signals (on some systems this is
   .. :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
   .. not all systems define the same set of signal names; only those names defined by
   .. the system are defined by this module.

   全てのシグナル番号はシンボル定義されています。例えば、ハングアップシグナルは :const:`signal.SIGHUP` で定義されています; 変数名は C
   言語のプログラムで使われているのと同じ名前で、 ``<signal.h>`` にあります。 ':cfunc:`signal`' に関する Unix
   マニュアルページでは、システムで定義されているシグナルを列挙しています (あるシステムではリストは :manpage:`signal(2)`
   に、別のシステムでは :manpage:`signal(7)` に列挙されています)。全てのシステムで同じシグナル名のセットを定義しているわけではないので
   注意してください; このモジュールでは、システムで定義されているシグナル名だけを定義しています。


.. data:: NSIG

   .. One more than the number of the highest signal number.

   最も大きいシグナル番号に 1 を足した値です。


.. data:: ITIMER_REAL

   .. Decrements interval timer in real time, and delivers :const:`SIGALRM` upon expiration.

   実時間でデクリメントするインターバルタイマーです。タイマーが発火したときに :const:`SIGALRM` を送ります。


.. data:: ITIMER_VIRTUAL

   .. Decrements interval timer only when the process is executing, and delivers
   .. SIGVTALRM upon expiration.

   プロセスの実行時間だけデクリメントするインターバルタイマーです。タイマーが発火したときに :const:`SIGVTALRM` を送ります。


.. data:: ITIMER_PROF

   .. Decrements interval timer both when the process executes and when the
   .. system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
   .. this timer is usually used to profile the time spent by the application
   .. in user and kernel space. SIGPROF is delivered upon expiration.

   プロセスの実行中と、システムがそのプロセスのために実行している時間だけデクリメントするインターバルタイマーです。
   ITIMER_VIRTUAL と組み合わせて、このタイマーはよくアプリケーションがユーザー空間とカーネル空間で消費した時間のプロファイリングに利用されます。
   タイマーが発火したときに :const:`SIGPROF` を送ります。


.. The :mod:`signal` module defines one exception:

:mod:`signal` モジュールは1つの例外を定義しています:


.. exception:: ItimerError

   .. Raised to signal an error from the underlying :func:`setitimer` or
   .. :func:`getitimer` implementation. Expect this error if an invalid
   .. interval timer or a negative time is passed to :func:`setitimer`.
   .. This error is a subtype of :exc:`IOError`.

   背後の :func:`setitimer` または :func:`getitimer` 実装からエラーを通知するために送出されます。
   無効なインタバルタイマーや負の時間が :func:`setitimer` に渡された場合、このエラーを予期してください。
   このエラーは :exc:`IOError` の特殊型です。


.. The :mod:`signal` module defines the following functions:

:mod:`signal` モジュールでは以下の関数を定義しています:


.. function:: alarm(time)

   .. If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
   .. sent to the process in *time* seconds. Any previously scheduled alarm is
   .. canceled (only one alarm can be scheduled at any time).  The returned value is
   .. then the number of seconds before any previously set alarm was to have been
   .. delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
   .. canceled.  If the return value is zero, no alarm is currently scheduled.  (See
   .. the Unix man page :manpage:`alarm(2)`.) Availability: Unix.

   *time* がゼロでない値の場合、この関数は *time* 秒後頃に :const:`SIGALRM` をプロセスに送るように要求します。
   それ以前にスケジュールしたアラームはキャンセルされます (常に一つのアラームしかスケジュールできません)。この場合、戻り値は以前に設定
   されたアラームシグナルが通知されるまであと何秒だったかを示す値です。 *time* がゼロの場合、アラームは一切スケジュールされず、現在
   スケジュールされているアラームがキャンセルされます。
   戻り値がゼロの場合、現在アラームがスケジュールされていないことを示します。(Unix マニュアルページ :manpage:`alarm(2)`
   を参照してください)。利用できる環境: Unix。


.. function:: getsignal(signalnum)

   .. Return the current signal handler for the signal *signalnum*. The returned value
   .. may be a callable Python object, or one of the special values
   .. :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`.  Here,
   .. :const:`signal.SIG_IGN` means that the signal was previously ignored,
   .. :const:`signal.SIG_DFL` means that the default way of handling the signal was
   .. previously in use, and ``None`` means that the previous signal handler was not
   .. installed from Python.

   シグナル *signalnum* に対する現在のシグナルハンドラを返します。戻り値は呼び出し可能な Python
   オブジェクトか、 :const:`signal.SIG_IGN`\ 、 :const:`signal.SIG_DFL`\ 、および :const:`None`
   といった特殊な値のいずれかです。ここで :const:`signal.SIG_IGN` は以前そのシグナルが
   無視されていたことを示し、 :const:`signal.SIG_DFL` は以前そのシグナルの標準の処理方法が使われていたことを示し、 ``None``
   はシグナルハンドラがまだ Python によってインストールされていないことを示します。


.. function:: pause()

   .. Cause the process to sleep until a signal is received; the appropriate handler
   .. will then be called.  Returns nothing.  Not on Windows. (See the Unix man page
   .. :manpage:`signal(2)`.)

   シグナルを受け取るまでプロセスを一時停止します; その後、適切なハンドラが呼び出されます。戻り値はありません。Windows では利用できません。(Unix
   マニュアルページ :manpage:`signal(2)` を参照してください。)


.. function:: setitimer(which, seconds[, interval])

   .. Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
   .. :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
   .. by *which* to fire after *seconds* (float is accepted, different from
   .. :func:`alarm`) and after that every *interval* seconds. The interval
   .. timer specified by *which* can be cleared by setting seconds to zero.

   *which* で指定されたタイマー (:const:`signal.ITIMER_REAL`, :const:`signal.ITIMER_VIRTUAL`,
   :const:`signal.ITIMER_PROF` のどれか) を、 *seconds* 秒後と (:func:`alarm` と異なり、floatを指定できます)、
   それから *interval* 秒間隔で起動するように設定します。
   *seconds* に0を指定すると、そのタイマーをクリアすることができます。


   .. When an interval timer fires, a signal is sent to the process.
   .. The signal sent is dependent on the timer being used;
   .. :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
   .. :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
   .. and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.

   インターバルタイマーが起動したとき、シグナルがプロセスに送られます。
   送られるシグナルは利用されたタイマーの種類に依存します。
   :const:`signal.ITIMER_REAL` の場合は :const:`SIGALRM` が、
   :const:`signal.ITIMER_VIRTUAL` の場合は :const:`SIGVTALRM` が、
   :const:`signal.ITIMER_PROF` の場合は :const:`SIGPROF` が送られます。


   .. The old values are returned as a tuple: (delay, interval).

   以前の値が (delay, interval) のタプルとして返されます。


   .. Attempting to pass an invalid interval timer will cause an
   .. :exc:`ItimerError`.  Availability: Unix.

   無効なインターバルタイマーを渡すと :exc:`ItimerError` 例外が発生します。
   利用できる環境: Unix


   .. versionadded:: 2.6


.. function:: getitimer(which)

   .. Returns current value of a given interval timer specified by *which*.
   .. Availability: Unix.

   *which* で指定されたインターバルタイマーの現在の値を返します。
   利用できる環境: Unix


   .. versionadded:: 2.6


.. function:: set_wakeup_fd(fd)

   .. Set the wakeup fd to *fd*.  When a signal is received, a ``'\0'`` byte is
   .. written to the fd.  This can be used by a library to wakeup a poll or select
   .. call, allowing the signal to be fully processed.

   wakeup fd を *fd* に設定します。
   シグナルを受信したときに、 ``'\0'`` バイトがそのfdに書き込まれます。
   これは、pollやselectをしているライブラリを起こして、シグナルの処理をさせるのに利用できます。


   .. The old wakeup fd is returned.  *fd* must be non-blocking.  It is up to the
   .. library to remove any bytes before calling poll or select again.

   戻り値は古い wakeup fd です。
   *fd* はノンブロッキングでなければなりません。
   起こされたライブラリは、次の poll や select を実行する前にこの fd からすべてのバイトを取り除かなければなりません。


   .. When threads are enabled, this function can only be called from the main thread;
   .. attempting to call it from other threads will cause a :exc:`ValueError`
   .. exception to be raised.

   スレッドが有効な場合、この関数はメインスレッドからしか実行できません。
   それ以外のスレッドからこの関数を実行しようとすると :exc:`ValueError` 例外が発生します。


.. function:: siginterrupt(signalnum, flag)

   .. Change system call restart behaviour: if *flag* is :const:`False`, system
   .. calls will be restarted when interrupted by signal *signalnum*, otherwise
   .. system calls will be interrupted.  Returns nothing.  Availability: Unix (see
   .. the man page :manpage:`siginterrupt(3)` for further information).

   システムコールのリスタートの動作を変更します。
   *flag* が :const:`False` の場合、 *signalnum* シグナルに中断されたシステムコールは再実行されます。
   それ以外の場合、システムコールは中断されます。戻り値はありません。
   利用できる環境: Unix (詳しい情報についてはマニュアルページ :manpage:`siginterrupt(3)` を参照してください)


   .. Note that installing a signal handler with :func:`signal` will reset the
   .. restart behaviour to interruptible by implicitly calling
   .. :cfunc:`siginterrupt` with a true *flag* value for the given signal.

   :func:`signal` を使ってシグナルハンドラを設定したときに、暗黙のうちに
   *flag* に true を指定して :cfunc:`siginterrupt` が実行されるため、
   中断に対するリスタートの動作がリセットされることに注意してください。


   .. versionadded:: 2.6


.. function:: signal(signalnum, handler)

   .. Set the handler for signal *signalnum* to the function *handler*.  *handler* can
   .. be a callable Python object taking two arguments (see below), or one of the
   .. special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`.  The previous
   .. signal handler will be returned (see the description of :func:`getsignal`
   .. above).  (See the Unix man page :manpage:`signal(2)`.)

   シグナル *signalnum* に対するハンドラを関数 *handler* にします。 *handler* は二つの引数 (下記参照) を取る呼び出し可能な
   Python オブジェクトか、 :const:`signal.SIG_IGN` あるいは :const:`signal.SIG_DFL`
   といった特殊な値にすることができます。以前に使われていたシグナルハンドラが返されます (上記の :func:`getsignal`
   の記述を参照してください)。 (Unix マニュアルページ :manpage:`signal(2)` を参照してください。)


   .. When threads are enabled, this function can only be called from the main thread;
   .. attempting to call it from other threads will cause a :exc:`ValueError`
   .. exception to be raised.

   複数スレッドの使用が有効な場合、この関数は主スレッドからのみ呼び出すことができます; 主スレッド以外のスレッドで呼び出そうとすると、例外
   :exc:`ValueError` が発生します。


   .. The *handler* is called with two arguments: the signal number and the current
   .. stack frame (``None`` or a frame object; for a description of frame objects,
   .. see the :ref:`description in the type hierarchy <frame-objects>` or see the
   .. attribute descriptions in the :mod:`inspect` module).

   *handler* は二つの引数とともに呼び出されます: シグナル番号、および現在のスタックフレーム (``None`` またはフレームオブジェクト; フレームオブジェクトに
   ついての記述は :ref:`標準型の階層における説明 <frame-objects>` か、 :mod:`inspect` モジュールの属性の説明を参照してください)。


.. _signal-example:

例
--

.. Here is a minimal example program. It uses the :func:`alarm` function to limit
.. the time spent waiting to open a file; this is useful if the file is for a
.. serial device that may not be turned on, which would normally cause the
.. :func:`os.open` to hang indefinitely.  The solution is to set a 5-second alarm
.. before opening the file; if the operation takes too long, the alarm signal will
.. be sent, and the handler raises an exception.

以下は最小限のプログラム例です。この例では :func:`alarm` を使ってファイルを開く処理を待つのに費やす時間を制限します;
例えば、電源の入っていないシリアルデバイスを開こうとすると、通常 :func:`os.open` は未定義の期間ハングアップしてしまいますが、
この方法はそうした場合に便利です。
ここではファイルを開くまで 5 秒間のアラームを設定することで解決しています; ファイルを
開く処理が長くかかりすぎると、アラームシグナルが送信され、ハンドラが例外を送出するようになっています。


::

   import signal, os

   def handler(signum, frame):
       print 'Signal handler called with signal', signum
       raise IOError("Couldn't open device!")

   # Set the signal handler and a 5-second alarm
   signal.signal(signal.SIGALRM, handler)
   signal.alarm(5)

   # This open() may hang indefinitely
   fd = os.open('/dev/ttyS0', os.O_RDWR)

   signal.alarm(0)          # Disable the alarm

