Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Output:
- ###############################################################################
- PID = [6606]
- th1 = 140563186882304
- The signal handler for thread: '140563186882304' receive: SIGUSR1
- SIGUSR2 was received
- th1 = exit
- ###############################################################################
- */
- #include <iostream>
- #include <pthread.h>
- #include <signal.h>
- #include <string.h>
- #include <sstream>
- void hdl(int sig)
- {
- std::cout << std::endl;
- std::string signal;
- if(sig == SIGUSR1)
- signal = "SIGUSR1";
- else if(sig == SIGUSR2)
- signal = "SIGUSR2";
- else
- signal = "Something else";
- std::cout << "The signal handler for thread: '" << pthread_self() << "' receive: " << signal << std::endl;
- }
- void show_me(void* arg)
- {
- std::stringstream str;
- str << (char*)arg << " = " << pthread_self() << std::endl;
- std::cout << str.str();
- }
- void show_exit(void* arg)
- {
- std::stringstream str;
- str << (char*)arg << " = " << "exit" << std::endl;
- std::cout << str.str();
- }
- void show_signal(int sig)
- {
- if(sig == SIGUSR1)
- std::cout << "SIGUSR1 was received\n";
- else if(sig == SIGUSR2)
- std::cout << "SIGUSR2 was received\n";
- else
- std::cout << "Received = " << sig << std::endl;
- }
- void* th_wait(void* arg)
- {
- show_me(arg);
- sigset_t set;
- sigemptyset(&set);
- sigaddset(&set, SIGUSR2);
- int sig;
- sigwait(&set, &sig);
- show_signal(sig);
- show_exit(arg);
- pthread_exit((void *)0);
- }
- int main()
- {
- std::cout << "PID = [" << getpid() << "]" << std::endl;
- struct sigaction act;
- memset(&act, 0, sizeof(act));
- act.sa_handler = hdl;
- sigset_t set;
- sigemptyset(&set);
- sigaddset(&set, SIGUSR1);
- sigaddset(&set, SIGUSR2);
- act.sa_mask = set;
- sigaction(SIGUSR1, &act, 0);
- sigaction(SIGUSR2, &act, 0);
- pthread_t th1;
- char s_th_1[] = "th1";
- pthread_create(&th1, NULL, th_wait, (void*)s_th_1);
- sleep(2);
- pthread_kill(th1, SIGUSR1);
- pthread_kill(th1, SIGUSR2);
- pthread_join(th1, NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement