Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Output:
- ################################################################################
- PID = [6498]
- th2 = 140463568520960
- th1 = 140463576913664
- The signal handler for thread: '140463592892192' receive: SIGUSR1
- The signal handler for thread: '140463568520960' receive: SIGUSR1
- th2 = exit
- The signal handler for thread: '140463576913664' receive: SIGUSR1
- 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_sleep(void* arg)
- {
- show_me(arg);
- sleep(30);
- show_exit(arg);
- }
- 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, th2;
- char s_th_1[] = "th1";
- char s_th_2[] = "th2";
- pthread_create(&th1, NULL, th_sleep, (void*)s_th_1);
- pthread_create(&th2, NULL, th_sleep, (void*)s_th_2);
- sleep(2);
- raise(SIGUSR1);
- pthread_kill(th1, SIGUSR1);
- pthread_kill(th2, SIGUSR1);
- pthread_join(th1, NULL);
- pthread_join(th2, NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement