16

私はcで完全に初心者です。システム コールにmypause()似た機能を持つ関数を作成し、シグナルを待機するブロックを繰り返すプログラムで関数をテストする必要があります。テ機能はどのように機能しますか?? このようなことはできません:pause()mypause()pause()mypause()

fprintf( stderr, "press any key to continue\n" );

プログラムをブロックしてシグナルを待つには?

pause()またはは使用できないことに注意してsigpause()ください。

4

1 に答える 1

15

関数はpause()シグナルが到着するまでブロックします。ユーザー入力は信号ではありません。シグナルは、別のプロセスまたはシステム自体によって発行される可能性があります。

Ctrl-Cたとえば、 を押すと、シェルSIGINTが現在実行中のプロセスにシグナルを送信し、通常はプロセスが強制終了されます。

ISO C99の動作をエミュレートするにはpause、次のように記述します。コードにはコメントが付けられています。この実装について質問がある場合は、質問してください。

#include <unistd.h>
#include <stdio.h>
#include <signal.h>

/**
 * The type sig_atomic_t is used in C99 to guarantee
 * that a variable can be accessed/modified in an atomic way
 * in the case an interruption (reception of a signal for example) happens.
 */
static volatile sig_atomic_t done_waiting = 0;

static void     handler()
{
  printf("Signal caught\n");
  done_waiting = 1;
}

void    my_pause()
{
  /**
   *  In ISO C, the signal system call is used
   *  to call a specific handler when a specified
   *  signal is received by the current process.
   *  In POSIX.1, it is encouraged to use the sigaction APIs.
   **/
  signal(SIGINT, handler);
  done_waiting = 0;
  while ( !done_waiting )
    ;
}

int     main()
{
  my_pause();
  printf("Hey ! The first call to my_pause returned !\n");
  my_pause();
  printf("The second call to my_pause returned !\n");
  return (0);
}

この例は、SIGINT信号でのみ機能することに注意してください。signal()追加のシグナル セットを処理するには、別のシグナル番号を使用して他の呼び出しを使用するかsigaction()、必要なすべてのシグナルを参照するマスクを使用します。

システムで使用可能なシグナルの完全なリストは、you <signal.h>include にあります。

于 2013-04-13T21:10:35.163 に答える