[erlang-questions] signal handler

Rick Pettit rpettit@REDACTED
Tue Jun 5 18:14:50 CEST 2007

On Tue, Jun 05, 2007 at 10:27:29AM +0530, Saifi Khan wrote:
> Hi:
> How does one write a signal handler in erlang ?

I'm not sure anyone does or even can (i.e. without spawning a separate UNIX

> I want to convert the following C code to Erlang:

Signals are handled by the emulator. I think you would be forced to spawn the
following as a separate UNIX process (erlang port) and do your signal handling

> #include <stdio.h>
> #include <stdlib.h>
> #include <sys/unistd.h>
> #include <signal.h>
> void ctrlc_handler(int sig)
> {
> 	char c;
> 	signal(sig, SIG_IGN);
> 	printf("ctrlc-handler called\n");
> 	printf("do you want to exit[y/n] ");
> 	c = getchar();
> 	if (c == 'y' || c == 'Y')
> 		exit(0);
> 	else
> 		signal(SIGINT, ctrlc_handler);
> }
> int main(int argc, char *argv[])
> {
> 	signal(SIGINT, ctrlc_handler);
> 	while (1)
> 		pause();
> 	return 0;
> }
> In the signal handler function 'ctrlc-handler',
> all the SIGINT signals that occur between the two signal calls
> cannot be caught.

On some operating systems it is necessary to reinstall a signal handler
every time it is called, assuming you want to keep handling the signal.

> Is this semantics carried over in Erlang as well ?

This isn't an erlang-specific issue, but rather an OS-dependent one.

And again, I don't think you are going to be able to (or should even try to)
install a signal handler from an erlang process. Even if you could it would
surely interfere with the emulator internals / runtime environment.

For example, I'm pretty sure the erlang shell already handles SIGINT--that's
why a Ctl-C at the shell yields something like the following:

  Eshell V5.5.2  (abort with ^G)
  BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
         (v)ersion (k)ill (D)b-tables (d)istribution

If you really must communicate with signals you should consider spawning an
external UNIX process as an erlang port via erlang:open_port/2.


More information about the erlang-questions mailing list