UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » Trouble with basic signal and alarm implementation

#1 2009-08-26 02:24 PM

shredder12
Member
Registered: 2009-06-07
Posts: 37

Re: Trouble with basic signal and alarm implementation

I was trying to implement a simple functionality in a program which will sniff icmp packets from a raw socket and if it doesn't find anything for 2 seconds an alarm will turn on and another function will be called.
I used the following code..

void signal_function(void);
void sniffing(void);

void sniffing(void)
{
        int sock_fd;
        unsigned char buffer[256] = {'\0'};

        sock_fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);

        while(read(sock_fd, buffer, 256) < 0)
        {
                ;
        }
        printf("packet\n");

        return;
}

void signal_function(void)
{
        printf("no packet caught yet\n");
        alarm(2);
        sniffing();

        return;
}

int main(void)
{
        signal(SIGALRM, (void *)&signal_function);
        alarm(2);
        sniffing();

        return 0;
}

I just want that the code should print that no packet is received yet if it is unable to sniff anything for 2 seconds.
It jst prints the statement once and never after that
where am I going wrong??

Offline

#2 2009-08-26 03:08 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Trouble with basic signal and alarm implementation

Because you call sniffing(); from your signal handler. As long as the signal
handler is running the signal that caused the call is blocked.

So remove that call from your signal handler and it should print out
something every two seconds, if signal(2) doesn't install a one shot
signal handler.

Offline

#3 2009-08-27 12:15 PM

shredder12
Member
Registered: 2009-06-07
Posts: 37

Re: Trouble with basic signal and alarm implementation

thanks i3839 .....  it worked..

Offline

  • Index
  • » C
  • » Trouble with basic signal and alarm implementation

Board footer

Powered by FluxBB