taleporos
taleporos

Reputation: 76

can't get out of while after signal use

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

void sigint_handler(int);

int  main()
{
    signal(SIGINT, sigint_handler);

     while (1){
         pause();
     }
    printf("Out..\n");
    return 0;
}

 void sigint_handler(int sig)
{

    printf("killing process %d\n",getpid());
    exit(0);
}

I dont get: Out... after ctrl+c So never returns on while or getting out. How can i fix it, to continiue in main, and print "Out..."?

Upvotes: 0

Views: 135

Answers (4)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58291

Don't use printf in sigint_handler, it may be undefined behavior. The list of safe functions that can be call in signal handler man page.
Explanation: Use reentrant functions for safer signal handling

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754820

If you want the loop in main() to exit under control, you have to make it a non-infinite loop. I'd probably do this:

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

static volatile sig_atomic_t sig_received = 0;
void sigint_handler(int);

int main(void)
{
    signal(SIGINT, sigint_handler);

    while (sig_received == 0)
        pause();
    printf("Out..\n");
    return 0;
}

void sigint_handler(int sig)
{
    sig_received = sig;
}

This meets the requirements of the C standard, which are far more stringent on what you're allowed to do in signal handlers than POSIX is.

Upvotes: 1

qulinxao
qulinxao

Reputation: 332

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

void sigint_handler(int);

int  main()
{
    signal(SIGINT, sigint_handler);


     pause();

    printf("Out..\n");
    return 0;
}

 void sigint_handler(int sig)
{

    printf("killing process %d\n",getpid());
    //exit(0);
}

Upvotes: 2

cnicutar
cnicutar

Reputation: 182714

I dont get: Out... after ctrl+c

Because the signal handler immediately ends the process so main never gets the chance of actually doing the printf. I suspect you don't actually want to exit in the handler. You should take the pause out of the loop and wait until the signal gets delivered.

This isn't the best way of waiting for a signal. For starters it is conceivable that the user could send the SIGINT before you get the chance to pause. The signal would be lost and pause(2) would block until the end of time.

You should probably use sigsuspend or the simpler sigpause.

Upvotes: 3

Related Questions