Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <signal.h>
- #include <pthread.h>
- #include <stdatomic.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <stdlib.h>
- /*
- * Set this variable if any signal is received
- */
- volatile sig_atomic_t sig_set_flag = 0;
- pthread_mutex_t cleanup_mutex;
- /*
- * Resource cleanup function.
- */
- int cleaup_resources() {
- pthread_mutex_lock(&cleanup_mutex);
- /*
- * Send notification to all the clients.
- * Delete all the temp files
- */
- printf("Notified to clients.Exiting process\n");
- pthread_mutex_unlock(&cleanup_mutex);
- return 0;
- }
- /*
- * Signal handler thread
- */
- void sig_term_handler(int sig_num) {
- sig_set_flag = sig_num;
- }
- int main()
- {
- int loop_count,status;
- pthread_t tid;
- pid_t pid;
- int ret;
- struct sigaction sig;
- sig.sa_handler = &sig_term_handler;
- sig.sa_flags = 0;
- sigaction(SIGHUP, &sig, NULL);
- /*
- * Spawn a thread to monitor signals.
- * If signal received, Exit the process.
- */
- while(1) {
- printf("Some time consuming task in progress... PID = %d\n",getpid());
- pid = fork();
- if(pid == 0) {
- sleep(100);
- return 0;
- } else {
- ret = waitpid(pid, &status, 0);
- if( (ret == -1) && (errno == EINTR) ) {
- printf("System call interrpted\n");
- }
- loop_count++;
- if( loop_count>=10)
- break;
- }
- }
- cleaup_resources();
- exit(0);
- }
Add Comment
Please, Sign In to add comment