Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does pause() work?

Tags:

c

I'm completely noob in c. I have to write a function mypause() that should have a functionality similar to the pause() system call, and test the mypause() function in a program that repeatedly blocks waiting for a signal. How does te pause() function works?? Can't I just do a mypause() like this:

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

in order for the program to block and wait for an signal?

Have in mind that I can't ever use pause() or sigpause().

like image 744
Luis Quesado Avatar asked Apr 13 '13 20:04

Luis Quesado


1 Answers

The pause() function blocks until a signal arrives. User inputs are not signals. A signal can be emitted by another process or the system itself.

Pressing Ctrl-C for instance, causes your shell to send a SIGINT signal to the current running process, which in normal cases causes the process to be killed.

In order to emulate the behaviour of pause in ISO C99 you could write something like the following. The code is commented, if you have a question about this implementation, please ask.

#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);
}

Note this example only works with the SIGINT signal. To handle an additional set of signals, you can use other calls to signal() with different signal numbers or use sigaction() with a mask referencing all the desired signals.

A complete list of the signals availables on your system can be found in you <signal.h> include.

like image 76
Halim Qarroum Avatar answered Sep 30 '22 02:09

Halim Qarroum