Inter-process communication-signal

Source: Internet
Author: User
Tags semaphore signal handler

1, the process of independence and collaboration

When the process runs in the operating system, each process is highly independent and closed! But some program problems require multiple processes to collaborate. At this time there is a contradiction.

Processes are highly independent and closed, and the process of collaboration will have to be communicated between processes. How to solve?

(1) To break the independence and closeness of the process; the consequences and risks of such a:i> lack of security;ii> increased coupling between processes. The solution is completely infeasible.

(2), to provide a number of media for the process, the process through the access to these media to achieve mutual communication purposes, so as to achieve inter-process collaboration.

Inter-process collaboration issues are transformed into inter-process communication issues.


2, inter-process communication

There are several means and methods for inter-process communication. The common methods are:

(1), the first can be used in inter-process communication is an important means: File system files , there are the following defects:i> access rules are not explicitly controlled;ii> access rule constraints can not reach the force;iii> low speed. (cpu> memory > files)

(2), in the file based on a new way: pipeline ( Special Memory area ). The following improvements have been made on the basis of the document. I> added a mandatory access rule fifo;ii> in order to speed up, use memory to mimic the file (in the way of file Operation memory area). Defects in the way pipelines are communicated: inflexible.

(3),IPC communication mode . Provides three modes of interprocess communication:i> shared memory;ii> semaphore;iii> Message Queuing. Use memory to build a special area that is separate from the physical memory of all processes. Given 3 mandatory rules to access this memory area; the communication tasks to be accomplished by the three rules are different.

A. Shared memory: data is shared among multiple processes.

B. Semaphore: Flags the number of shared resources for the process, and gives the lock mechanism.

C. Message Queuing: Complete a pipeline-like task, one-way flow of data .

(4), signal communication mode. Interrupt mode of communication, and the signal is called an interrupt. There is only one message for the signal to be communicated: a certain event occurs.


3. What is a signal

signal communication mode. Interrupt mode of communication, and the signal is called an interrupt. There is only one message for the signal to be communicated: a certain event occurs.

the simple signal is meaningless, the signal needs and the signal processing function (interrupt function). The meaning of this is: when a certain event (signal) occurs, you need to deal with what.

Interrupt: Interrupts the task being performed by the current process, creates a breakpoint (to protect the scene), and then executes the interrupt handler corresponding to the interrupt signal, returns a breakpoint (recovery field) after executing the interrupt handler function, and resumes the previous task.

One of the biggest features of interrupts: the call timing of an interrupt handler is completely indeterminate, depending on how long the interrupt signal occurred and how many times it occurred.


4. How does the signal occur?

The occurrence of the signal is divided into two kinds of:i> hardware caused by the;ii> software. According to this characteristic, the signal is divided into: soft interrupt and hard interrupt.

Hard interrupts, such as: CPU time fragments, bus interrupts, disk read and write interrupts, etc...

Soft interrupts, such as: Segment error interrupt, terminal interrupt, termination process run interrupt ...

Soft interrupts are generated by the operating system kernel or user process.


5. Signal transmission

at the level of the user process, the interrupt signal must be sent to the specified process after it has been generated!


6. Reception and processing of signals

The signal must be for the process to receive and then do the related processing.

The first step, the process can choose to process the signal or shielding signal, from this angle signal is divided into 2 kinds of:i> can be shielded signal (interrupt)

ii> non-blocking signal (interrupt).

In the second step, if the process chooses not to mask the signal, then the signal processing function (signal-to-signal processing function one by one corresponds) is called------. Therefore, within the process, a signal number and signal processing function corresponding table------interrupt vector table is required.

The interrupt vector table contains two main contents: the number of the signal and the function address of the signal processing function.

In addition, the shielding of the signal is controlled by a 8-byte 64-bit signal-blocking word. Each bit represents a signal, so the entire process can use less than 64 signals available. The number of the signal is the corresponding binary subscript.

Signal number
First address of function
1
Exit
2
Exit
..........

11
Perror () exit ()
..........

31

34

............

64

The Kill-l command allows you to view the number of available signals provided in the system.

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M00/87/4F/wKiom1fcAxXigQ3zAACltRc8ll4418.png-wh_500x0-wm_3 -wmp_4-s_2964767214.png "title=" Qq20160916223412.png "alt=" Wkiom1fcaxxigq3zaacltrc8ll4418.png-wh_50 "/>

Question: Why is the interrupt signal not designed to be extensible?


7, the origin of the interrupt vector table

Each process has its own interrupt vector table. Each process can maintain and manage its own interrupt vector table. The process has a complete interrupt vector table at the beginning of the creation. part of the signal is pre-defined interrupt processing function, such as signal 2, which corresponds to the exit (0) function call. The rest of the signals are not pre-defined interrupt handlers, and the signals of those predefined terminal handlers correspond to a function that resembles an empty function.

Question: When you fork a child process, is the interrupt vector table of the child process the same as the parent process?

The child process inherits the interrupt vector table of the parent process, provided that the function of the EXECV function family is not called.

If the resulting child process executes the system call of the EXECV function family, the interrupt vector table is rebuilt in the execution of the EXECV, based on the template of the interrupt vector table provided by the operating system kernel.


8. Programming control Signal

Programming control signals mainly do these aspects of Operation:i> signal capture;ii> signal generation;iii> signal programming considerations.

(1), signal capture: When the signal arrives at the process, the process can capture, identify the signal, and execute the signal corresponding processing function. In fact, you just need to control the interrupt vector table in the process.

When the signal is reached, the process executes the corresponding signal processing function immediately. This scheduling process is controlled by computer hardware-interrupt processing chip. So when programming, so-called signal capture is simply a signal processing function to set the corresponding signal number, that is, modify the interrupt vector table.

You only need to use the signal () function in programming.

#include <signal.h>typedef void (*sighandler_t) (int); sighandler_t signal (int signum, sighandler_t handler);

The first parameter: the number of the signal, the second parameter: The function pointer, executes our own signal processing function (does not perform the original system signal processing function). The return value that holds the address of the handler function for the original interrupt vector table.

code example:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> void Catch_  SIGINT (int sig) {printf ("Ctrl + C has happened, sig=%d\n", SIG);   The parameter is the corresponding transmitted signal number}int main (void) {signal (SIGINT, catch_sigint);    The number of the macro or corresponding signal that writes the signal can be. while (1) {printf ("Yes I am still alive.        \ n ");    Sleep (5); }   }

Operation Result:

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M02/87/4F/wKiom1fcDQGw3suiAABse7mUtYI316.png-wh_500x0-wm_3 -wmp_4-s_694969233.png "title=" Qq20160916231707.png "alt=" Wkiom1fcdqgw3suiaabse7mutyi316.png-wh_50 "/>

(2), the Generation of signals: by programming a process to produce a signal is a soft interrupt signal. Signal generation must have a signal to be transmitted to the target.

There are multiple APIs for generating a signal

function name
description
kill ()

int Kill (pid_t pid, int sig);

Send signal to the process specified by PID sig

raise ()

Send signal to current process

Equivalent to

Kill (Getpid (), signal)

alarm ()
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> void  catch_sigint (Int sig) {    printf ("ctrl + c has happened,  sig=%d\n ",  sig);  }void catch_sigalrm (Int sig) {    printf (" the alarm rang, It's time to get up \ n "); Int main (void) {    signal (sigint, catch_sigint);    // The number of the macro or corresponding signal that writes the signal can be.     signal (SIGALRM,&NBSP;CATCH_SIGALRM);     while (1) {         printf ("yes i am still alive. \n");     //  kill (Getpid (),  sigint);         raise ( SIGINT);  //These two functions are equivalent to         alarm (2);  //does not write this processing function, Following the system exit (0), the current process exits.         sleep (5);     }   }

At this point, it will only take 2 seconds to loop back, not to sleep for 5 seconds.

Alarm () has our own signal processing function, otherwise, 2 seconds to exit the current process (the system processes this signal function as: Exit (0)).


9. Some special signals

The SIGCHLD signal, which is generated at the end of the child process, is sent to the parent process of the child process. This is because the operating system needs to let the parent process know the end of the child process. The parent process needs to call the Wait () method at this point in response to the operating system, confirming that a message has been received that the child process has ended

The wait () method can only be used in processes that have child processes, and if a process does not have child processes, calling the wait () method fails!

The wait () method is used to handle the end state of a child process, while explicitly informing the operating system that the kernel has processed the end of the child process, allowing the operating system to fully reclaim the PCB information of the child process.

However, how can the wait () method cause the parent process to block and pause?

Scenario: (1), capture the SIGCHLD signal in the parent process, and call wait in the signal handler function.

This avoids both the zombie process and the parent process from being blocked.

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h>void catch _SIGCHLD (Int sig) {    printf ("one child has gone pid =  [%d], %d\n,  getpid (),  sig);     int ret = wait (NULL);     if (ret < 0) {         perror ("");     }   }int main (void) {    pid_t pid;     signal (SIGCHLD,&NBSP;CATCH_SIGCHLD);//parent-child processes can capture this signal     pid =  Fork ();     if (pid == 0) {          printf ("this is child %d\n",  getpid ());         Sleep (3);     }else if (pid > 0) {          while (1){            printf ("This is father  %d\n ",  getpid ());             sleep (1);         }    }else{         perror ("");     }    return 0;}

Run results

(1), the Wait () method is called when there is no child process.

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M02/87/4D/wKioL1fcaHmSOmxBAAAR9cvPN0c524.png-wh_500x0-wm_3 -wmp_4-s_517808038.png "title=" Qq20160917054720.png "alt=" Wkiol1fcahmsomxbaaar9cvpn0c524.png-wh_50 "/>

(2), the Wait () method is written in the signal processing function, which resolves the parent process's blocking (no zombie process is generated at this time).

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M02/87/4D/wKioL1fcaQDCkpp_AABPWuuGdpE742.png-wh_500x0-wm_3 -wmp_4-s_854342928.png "title=" Qq20160917054939.png "alt=" Wkiol1fcaqdckpp_aabpwuugdpe742.png-wh_50 "/>

The end of the child process, the sending signal sigchld is captured by the parent process.


10, the flood of the signal

After the signal is generated and sent to a process, it can be provided to the process for processing the signal for a very short time, with only a few CPU clock cycles. If the process does not explicitly process the signal during this very limited time, the signal disappears immediately.

when a signal is captured and executing, the same signal cannot be triggered immediately, and if the signal is being processed, the new signal will be discarded.

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h>void catch _SIGUSR1 (Int sig) {    printf ("this is %d signal \n",  sig);     sleep (1);} Int main (void) {    signal (SIGUSR1,&NBSP;CATCH_SIGUSR1);     int  i = 0;    pid_t pid;    pid = fork ();     if (pid == 0) {         sleep (1);         for (;  i < 50; i++) {             kill (Getppid (), &NBSP;SIGUSR1);         }       }else{         while (1) {            sleep(1);            }        }       return 0;

Run results

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M00/87/4D/wKioL1fcbpvi7MM3AAAdYi7U2fY515.png-wh_500x0-wm_3 -wmp_4-s_4056541847.png "title=" Qq20160917061332.png "alt=" Wkiol1fcbpvi7mm3aaadyi7u2fy515.png-wh_50 "/>

50 times the result of the signal is captured and printed on the screen, the signal is flooded, and all is printed only once.


11. reentrant function

In front of the signal, there are 2 types of signals, which can be re-entered and non-reentrant functions. The most classic non-reentrant function is malloc ();

Assuming that the malloc () method is called in the program, and that an interrupt occurs while the malloc () is being called, it is necessary to execute the corresponding handler for the interrupt, and coincidentally, the malloc () function is also called in the interrupt handler, is there a problem at this point?

Re-entry: Because of the existence of interrupts, as well as the randomness of the timing of the interruption, it is possible that a function is called once in the interrupt handler (equivalent to calling itself once again in the function) when it has not yet been called.

in this case, some functions are non-reentrant because the situation becomes unstable and error prone.

in this case, some functions can accommodate this situation, which is a reentrant function.


12, mysleep--imitate sleep () function

Implementation code:

#include <stdio.h> #include <unistd.h> #include <signal.h> #include <stdlib.h> #include <sys  /types.h>void catch_sigalrm (int sig) {//Capture alarm signal function processing}void mysleep (int seconds) {alarm (seconds);    Write the capture function of the alarm signal, otherwise the exit (0) of the calling system will exit.  Pause ();    Pause}int Main (void) {signal (SIGALRM, CATCH_SIGALRM);        while (1) {printf ("'ll Sleep Seconds by mysleep\n");    Mysleep (1); } return 0;}

Run results

650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M00/87/50/wKiom1fcc6Oh16k_AABeqace8y8417.png-wh_500x0-wm_3 -wmp_4-s_3356219874.png "title=" Qq20160917063503.png "alt=" Wkiom1fcc6oh16k_aabeqace8y8417.png-wh_50 "/>

This simulates the sleep () function with a lot of holes.



This article is from the "11586096" blog, please be sure to keep this source http://11596096.blog.51cto.com/11586096/1853259

Inter-process communication-signal

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.