Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Make the process sleep for SECONDS seconds, or until a signal arrives
- and is not ignored. The function returns the number of seconds less
- than SECONDS which it actually slept (zero if it slept the full time).
- If a signal handler does a `longjmp' or modifies the handling of the
- SIGALRM signal while inside `sleep' call, the handling of the SIGALRM
- signal afterwards is undefined. There is no return value to indicate
- error, but if `sleep' returns SECONDS, it probably didn't work. */
- /* sleep has a signal handler that stops on sigalrm
- * lets check it out:
- * Two threads, one to send events, one to sleep */
- #include <unistd.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <signal.h>
- #include <stdio.h>
- #include <string.h>
- char buffer[2000];
- void * sleeping();
- void handle_signal(int i);
- int main(void)
- {
- /* setup thread */
- pthread_t sleeper;
- if(pthread_create(&sleeper, NULL, sleeping, NULL) != 0)
- {
- printf("Could not start sleeper thread\n");
- }
- /* interrupt sleeping thread on user input */
- printf("Send a message to the sleeper\n");
- while(1)
- {
- fgets(buffer, 2000, stdin);
- raise(SIGALRM);
- }
- /* join: this will never happen the way this is implemented */
- pthread_join(sleeper, NULL);
- exit(0);
- }
- void * sleeping()
- {
- /* handle SIGALRM */
- struct sigaction action;
- sigset_t set;
- memset(&action, 0, sizeof(action));
- sigemptyset(&action.sa_mask);
- action.sa_flags = 0;
- action.sa_handler = handle_signal;
- sigaction(SIGALRM, &action, NULL);
- /* sleep until we get signal */
- while(1)
- {
- sleep(100000);
- printf("Woke Up!\n"); // when we run this never prints
- // which means after the sigalrm
- // we go back to sleep
- // while the default handling does not
- }
- }
- void handle_signal(int sig)
- {
- /* exit - make thread exit */
- if(strstr(buffer, "exit") != NULL)
- {
- exit(0);
- }
- else // echo message
- {
- write(1, "your message: ", 15);
- write(1, buffer, 2000);
- write(1, "\n", 2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement