Interrupted system call in C

I want my program to sleep up to 10 seconds, even when the signal has been reached. So, I tried the following program.

Program:

#include<stdio.h>
#include<signal.h>
#include<errno.h>
int main()
{
    printf("PID: %d\n",getpid());
    int unslept=10;
    while(unslept>0){
        unslept=sleep(unslept);
        if(errno==EINTR)
            continue;
    }
    return 0;
}

Output:

$ ./a.out 
PID: 18935
User defined signal 1
$

I expect the above program to execute 10 seconds, even if the signal is interrupted. I do this, for example, in one terminal I executed this program. And using another terminal, using the kill command, I sent the signal SIGUSR1 to this process. But, the same problem takes place. As soon as the signal is transmitted, the program ends. So, is there a way to execute my program for up to 10 seconds without affecting any signal.

+4
source share
2 answers

. , , .

// signal handler
    void my_function(int sig){
      //do nothing
    }

// register signal
    signal(SIGNAL_ID, my_function);  
+1

. . , , SIGUSR1 , SIG_IGN.

#include<stdio.h>
#include<signal.h>

    int main(void)
    {
            if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)
                    perror("SIGUSR1");

            sleep(30);
    }
+1

Source: https://habr.com/ru/post/1613829/


All Articles