Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When you press <kbd>Ctr + C</kbd>, the operating system sends a <a href="http://en.wikipedia.org/wiki/Signal_programming" rel="noreferrer">signal</a> to the process. There are many signals and one of them is SIGINT. The SIGINT ("program interrupt") is one of the Termination Signals. </p> <p>There are a few more kinds of Termination Signals, but the interesting thing about SIGINT is that it can be handled (caught) by your program. The default action of SIGINT is program termination. That is, if your program doesn't specifically handle this signal, when you press <kbd>Ctr + C</kbd> your program terminates as the default action. </p> <p>To change the default action of a signal you have to register the signal to be caught. To register a signal in a C program (at least under POSIX systems) there are two functions </p> <ol> <li><a href="http://linux.die.net/man/2/signal" rel="noreferrer">signal(int signum, sighandler_t handler);</a> </li> <li><a href="http://linux.die.net/man/2/sigaction" rel="noreferrer">sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);</a>. </li> </ol> <p>These functions require the header <a href="http://linux.die.net/man/2/signal" rel="noreferrer">signal.h</a> to be included in your C code. I have provide a simple example of the <code>signal</code> function below with comments.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;signal.h&gt; // our new library volatile sig_atomic_t flag = 0; void my_function(int sig){ // can be called asynchronously flag = 1; // set flag } int main(){ // Register signals signal(SIGINT, my_function); // ^ ^ // Which-Signal |-- which user defined function registered while(1) if(flag){ // my action when signal set it 1 printf("\n Signal caught!\n"); printf("\n default action it not termination!\n"); flag = 0; } return 0; } </code></pre> <p>Note: you should only call <a href="http://man7.org/linux/man-pages/man7/signal.7.html" rel="noreferrer">safe/authorized functions</a> in signal handler. For example <a href="https://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler/16891065#16891065">avoid calling printf in signal handler</a>.</p> <p>You can compile this code with gcc and execute it from the shell. There is an infinite loop in the code and it will run until you send a <code>SIGINT</code> signal by pressing <kbd>Ctr + C</kbd>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload