Linux Signals and multithreading

Source: Internet
Author: User
Tags signal handler

The use of signaling mechanisms in multi-threaded Linux is fundamentally different from the use of signaling mechanisms in the process. In the process environment, the signal processing is to register the signal processing function, when the signal occurs asynchronously, call the processing function to process the signal. It is completely asynchronous (we have no idea that the signal will arrive at the execution point of the process!) )。 However, the implementation of signal processing function has many limitations, such as some functions cannot be called in the signal processing function, such as some functions read, recv and other calls will be asynchronous signal to interrupt (interrupt), So we have to deal with situations where these functions are interrupted by signals when they are called (judging whether Enno equals eintr when the function returns).


But the principle of processing the signal in multi-threading is completely different, and the basic principle is: to process the signal asynchronously, convert to synchronous processing, which means that a thread is dedicated to the arrival of a "synchronous wait" signal, while other threads can be completely disconnected/interrupted by the signal (interrupt). This simplifies the processing of signals in a multithreaded environment to a considerable extent. It is also possible to ensure that other threads are not affected by the signal. So we can fully predict the signal, because it is no longer asynchronous, but synchronous (we know exactly which execution point in the thread the signal will come in and be processed!) )。 Synchronous programming patterns are always simpler than asynchronous programming patterns. In fact, multi-threading compared to one of the advantages of multi-process is: Multithreading can be asynchronous in the process of converting things into synchronous processing. 1. sigwait function:
  1. Sigwait-wait for a signal
  2. #include <signal.h>
  3. int sigwait (CONST sigset_t *set, int *sig);

  4. Description
  5. The sigwait () function suspends execution of the calling thread until the delivery of one
  6. Of the signals specified in the signal set set. The function accepts the signal (removes
  7. It from the pending list of signals), and returns the signal number in sig.
  8. The operation of Sigwait () is the same as Sigwaitinfo (2), except that:
  9. * SIGWAIT () only returns the signal number, rather than a siginfo_t structure describing
  10. The signal.
  11. * The return values of the functions are different.
  12. Return Value
  13. On success, sigwait () returns 0. On error, it returns a positive error number.
From the description of the man sigwait above, we know: Sigwait is SyncWait for the signal to arrive, instead of waiting for the signal to be asynchronous like in the process. The sigwait function uses a signal set as his parameter, and returns the signal value when any signal in the set occurs, unblocking it, and can then perform some corresponding processing on the signal. 2. Remember:In multithreaded code, a function such as sigwait or Sigwaitinfo or sigtimedwait is always used to process the signal. Instead of functions such as signal or sigaction. Because a function called signal or sigaction in one thread changes the signal handler function in the thread. Instead of just changing the signal processing function of the thread that called Signal/sigaction. 3. Pthread_sigmask function:Each thread has its own set of signal masks (the signal mask),You can use the Pthread_sigmask function to block a thread from certain signalsresponse processing, leaving only the thread that needs to process the signal to process the specified signal. Implementation by using the inheritance relationship of the thread signal masking set(after the sigmask is set in the main process, the thread created by the main process inherits the mask of the main process)
  1. Pthread_sigmask-examine and change mask of blocked signals
  2. #include <signal.h>
  3. int pthread_sigmask (int how, Const sigset_t *Set, sigset_t *oldset);
  4. Compile and Link with-pthread.
  5. DESCRIPTION
  6. The Pthread_sigmask () function is a just like Sigprocmask (2), with the difference , it use
  7. In multithreaded programs are explicitly specified by posix.1-2001.
  8. Other differences is noted in the this page.
  9. For a description of the arguments and operation of this function, see Sigprocmask (2).
  10. RETURN VALUE
  11. On success, Pthread_sigmask () returns 0; On error, it returns an error number.
  12. NOTES
  13. A new thread inherits a copy of its creator ' s signal mask.
  14. (From Mans Sigprocmask:)
  15. The behavior of the dependent on the value of what, as follows.
  16. Sig_block
  17. The set of blocked signals is the union of the current set and the set argument.
  18. Sig_unblock
  19. The signals in set is removed from the current set of blocked signals. It is permissible
  20. To attempt to unblock a signal which are not blocked.
  21. Sig_setmask
  22. The set of blocked signals is set to the argument set.
  23. If oldset is Non-null, the previous value of the signal mask was stored in oldset.
  24. If Set is NULL and then the signal mask is unchanged (i.e., what is ignored)
  25. Value of the signal mask is nevertheless returned in Oldset (if it was not NULL).
4. Pthread_kill function:In a multithreaded program, a thread can use Pthread_kill to send a signal to a specified thread (including itself) in the same process. Note the KILL function is generally not used in multiple threads to send a signal because kill is sending a signal to the process, as a result: The running thread will process the signal, and if the thread does not register a signal handler, it will cause the entire process to exit.
    1. #include <signal.h>
    2. int Pthread_kill (pthread_t  thread , int   sig );
    3. Compile and link with-pthread.
    4. DESCRIPTION
    5. the Pthread_kill () function sends the SIGNAL&NBSP; sig  to thread, Anoth Er thread in the same 
    6. process as the caller. The signal is asynchronously directed to thread.
    7. if  Sig  is 0, then no signal was sent, but error checking was still performed; this can be& nbsp;
    8. used to check for the existence of a thread ID.
    9. RETURN VALUE
    10. on Success, Pthread_kill () returns 0; "On" error, it returns an Error number, and No signal 
    11. is sent.
    12. ERRORS
    13. esrch No thread with the ID of thread could be found.
    14. EINVAL An invalid signal is specified.
5. Remember: The signal that calls the sigwait synchronous wait must be masked in the calling thread and should usually be masked in all threads (so that the signal is never sent to any other thread other than the call to Sigwait), which is achieved by using the inheritance relationship of the signal mask. (The semantics of sigwait require, all threads (including the thread calling sigwait) has the signal masked, for rel Iable operation. Otherwise, a signal, arrives not blocked in sigwait might is delivered to another thread.) 6. Code example :(from Mans Pthread_sigmask)
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <signal.h>
  6. #include <errno.h>
  7. /* Simple error handling functions */
  8. #define Handle_error_en (en, msg) \
  9. do {errno = en, perror (msg); exit (exit_failure);} while (0)
  10. static void *
    1. Sig_thread (void *arg)
  11. {
  12. sigset_t *set = (sigset_t *) arg;
  13. int S, SIG;
  14. for (;;) {
  15. s = sigwait (set, &sig);
  16. if (s! = 0)
  17. Handle_error_en (S, "sigwait");
  18. printf ("Signal handling thread got Signal%d\n", SIG);
  19. }
  20. }
  21. int
    1. Main (int argc, char *argv[])
  22. {
  23. pthread_t thread;
  24. sigset_t set;
  25. int s;
  26. /*
  27. Block SIGINT; Other threads created by main () would inherit
  28. A copy of the signal mask.
  29. */
  30. Sigemptyset (&set);
  31. Sigaddset (&set, sigquit);
  32. Sigaddset (&set, SIGUSR1);
  33. s = Pthread_sigmask (Sig_block, &set, NULL);
  34. if (s! = 0)
  35. Handle_error_en (S, "pthread_sigmask");
  36. s = pthread_create (&thread, NULL, &sig_thread, (void *) &set);
  37. if (s! = 0)
  38. Handle_error_en (S, "pthread_create");
  39. /*
  40. Main thread carries on to create other threads and/or do
  41. Other work
  42. */
  43. Pause (); /* Dummy Pause so we can test program */
  44. return 0;
  45. }
Compile run:
    1. [Email protected]:~/pthread/learnthread$ gcc-wall-pthread-o pthread_sigmask pthread_sigmask.c
    2. [Email protected]:~/pthread/learnthread$./pthread_sigmask &
    3. [1] 4170
    4. [Email protected]:~/pthread/learnthread$ kill-quit%1
    5. [Email protected]:~/pthread/learnthread$ Signal handling thread got Signal 3
    6. [Email protected]:~/pthread/learnthread$ kill-usr1%1
    7. [Email protected]:~/pthread/learnthread$ Signal handling thread got Signal 10
    8. [Email protected]:~/pthread/learnthread$ kill-term%1
    9. [Email protected]:~/pthread/learnthread$
    10. [1]+ Terminated./pthread_sigmask
    11. [Email protected]:~/pthread/learnthread$
This example shows that by blocking some signals in the main thread, the other threads inherit the signal mask, and then use the Sigwait function exclusively with one thread to synchronously process the signal so that other threads are not affected by the signal.

Linux signals and multithreading

Related Article

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.