IPC: interrupts and Signals

Source: Internet
Author: User
Tags signal handler

In this section will look at ways in which two processes can communicate. when a process terminates abnormally it usually tries to send a signal indicating what went wrong. C Programs (and UNIX) can trap these for diagnostics. also user specified communication can take place in this way.

Signals are software generated interrupts that are sent to a process when a event happens. signals can be synchronously generated by an error in an application, suchSigfpeAndSIGSEGV, But most signals are asynchronous. signals can be posted to a process when the system detects a software event, such as a user entering an interrupt or stop or a kill request from another process. signals can also be come directly from the OS Kernel when a hardware event such as a bus error or an illegal instruction is encountered. the system defines a set of signals that can be posted to a process. signal delivery is analogous to hardware interrupts in that a signal can be blocked from being delivered in the future. most signals cause termination of the processing process if no action is taken by the process in response to the signal. some signals stop the processing process and other signals can be ignored. each signal has a default action which is one of the following:

  • The signal is discarded after being passed ed
  • The process is terminated after the signal is already ed
  • A core file is written, then the process is terminated
  • Stop the process after the signal is already ed

Each signal defined by the system falls into one of five classes:

 

  • Hardware Conditions
  • Software Conditions
  • Input/Output notification
  • Process Control
  • Resource Control

Macros are defined in<Signal. h>Header file for common signals.

These include:

Sighup 1/* hangup */ SIGINT 2/* interrupt */
Sigquit 3/* Quit */ Sigill 4/* illegal instruction */
SIGABRT 6/* used by abort */ Sigkill 9/* hard kill */
Sigalrm 14/* Alarm clock */  
Sigcont 19/* continue a stopped process */  
Sigchld 20/* to parent on child stop or exit */  

SignalsCan be numbered from 0 to 31.

 

Sending signals -- Kill (), raise ()

There are two common functions used to send signals

Int kill (int pid, int signal)-A system call that sendsSignalTo a process,PID. If PID is greater than zero, the signal is sent to the process whose process ID is equal to PID. If PID is 0, the signal is sent to all processes, wait t system processes.

Kill ()Returns 0 for a successful call,-1 otherwise and setsErrnoAccordingly.

Int raise (INT sig)Sends the signal sig to the executing program.Raise ()Actually usesKill ()To send the signal to the executing program:

 

          kill(getpid(), sig);

There is also a Unix Command called kill that can be used to send signals from the command line-seeManPages.

Note: That unless caught or ignored,KillSignal terminates the process. Therefore protection is built into the system.

Only processes with certain access privileges can be killed off.

Basic rule:Only processes that have the same user can send/receive messages.

TheSigkillSignal cannot be caught or ignored and will always terminate a process.

 

For exampleKill (getpid (), SIGINT );Wocould send the interrupt signal to the ID of the calling process.

This wowould have a similar effectExit ()Command. AlsoCTRL-CTyped from the command sendsSIGINTTo the process currently being.

Unsigned int alarm (unsigned int seconds)-- Sends the signalSigalrmTo the invoking process after seconds.

 

Signal Handling -- Signal ()

An application program can specify a function called a signal handler to be invoked when a specific signal is wrongly ed. when a signal handler is invoked on receept of a signal, it is said to catch the signal. A process can deal with a signal in one of the following ways:

  • The process can let the default action happen
  • The process can block the signal (some signals cannot be ignored)
  • The process can catch the signal with a handler.

Signal handlers usually execute on the current stack of the process. this lets the signal handler return to the point that execution was interrupted in the process. this can be changed on a per-signal basis so that a signal handler executes on a special stack. if a process must resume in a different context than the interrupted one, it must restore the previous context itself

Signing ing signals is straighforward with the function:

INT (* signal (INT Sig, void (* func )()))()-- That is to say the FunctionSignal ()Will callFuncFunctions if the process has es a signalSIG. Signal returns a pointer to functionFuncIf successful or it returns an errorErrnoAnd-1 otherwise.

 

Func ()Can have three values:

 

Sig_dfl
-- A pointer to a system default Function Sid_dfl (), Which will terminate the process upon receipof SIG.
Sig_ign
-- A pointer to system ignore Function Sig_ign ()Which will disregard SIGAction (unless it is Sigkill).
A function address
-- A user specified function.

Sig_dfl and sig_ignAre defined inSignal. h(Standard library) header file.

Thus to ignoreCTRL-CCommand from the command line. We cocould do:

Signal (SIGINT, sig_ign );

To reset system so thatSIGINTCauses a termination at any place in our program, we wowould do:

Signal (SIGINT, sig_dfl );

 

So lets write a program to trapCTRL-CBut not quit on this signal. We have a functionSigproc ()That is executed when we trapCTRL-C. We will also set another function to quit the program if it trapsSigquitSignal so we can terminate our program:

#include <stdio.h> void sigproc(void); void quitproc(void);  main(){ signal(SIGINT, sigproc); signal(SIGQUIT, quitproc); printf(``ctrl-c disabled use ctrl- to quitn''); for(;;); /* infinite loop */} void sigproc(){  signal(SIGINT, sigproc); /*  */ /* NOTE some versions of UNIX will reset signal to default after each call. So for portability reset signal each time */  printf(``you have pressed ctrl-c n'');} void quitproc(){  printf(``ctrl- pressed to quitn''); exit(0); /* normal exit status */}

 

 

Sig_talk.c-- Complete example Program

Let us now write a program that communicates between child and parent processes usingKill () and signal ().

Fork ()Creates the child process from the parent.PIDCan be checked to decide whether it is the child (= 0) or the parent (pid = child process ID ).

The parent can then send messages to child using the PID andKill ().

The child picks up these signalsSignal ()And callappropriate functions.

An example of communicating process using signals isSig_talk.c:

 

/* sig_talk.c --- Example of how 2 processes can talk *//* to each other using kill() and signal() *//* We will fork() 2 process and let the parent send a few *//* signals to it`s child  *//* cc sig_talk.c -o sig_talk  */#include <stdio.h>#include <signal.h>void sighup(); /* routines child will call upon sigtrap */void sigint();void sigquit();main(){ int pid;  /* get child process */     if ((pid = fork()) < 0) {        perror("fork");        exit(1);    }       if (pid == 0)     { /* child */       signal(SIGHUP,sighup); /* set function calls */       signal(SIGINT,sigint);       signal(SIGQUIT, sigquit);       for(;;); /* loop for ever */     }  else /* parent */     {  /* pid hold id of child */       printf("/nPARENT: sending SIGHUP/n/n");       kill(pid,SIGHUP);       sleep(3); /* pause for 3 secs */       printf("/nPARENT: sending SIGINT/n/n");       kill(pid,SIGINT);       sleep(3); /* pause for 3 secs */       printf("/nPARENT: sending SIGQUIT/n/n");       kill(pid,SIGQUIT);       sleep(3);     }}void sighup(){  signal(SIGHUP,sighup); /* reset signal */   printf("CHILD: I have received a SIGHUP/n");}void sigint(){  signal(SIGINT,sigint); /* reset signal */   printf("CHILD: I have received a SIGINT/n");}void sigquit(){ printf("My DADDY has Killed me!!!/n");  exit(0);}

 

Other Signal Functions

There are a few other functions defined inSignal. h:

Int sighold (INT sig)-- AddsSIGTo the calling process's signal mask

Int sigrelse (INT sig)-- RemovesSIGFrom the calling process's signal mask

Int sigignore (INT sig)-- Sets the dispositionSIGToSig_ign

Int sigpause (INT sig)-- RemovesSIGFrom the calling process's signal mask and suspends the calling process until a signal is wrongly ed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.