recvsig.c

Dan McDonald, 2014-07-18 08:24 PM

Download (960 Bytes)

 
1
#include <sys/socket.h>
2
#include <sys/sockio.h>
3
#include <netinet/in.h>
4
#include <sys/signal.h>
5
#include <sys/filio.h>
6
#include <stdio.h>
7
#include <unistd.h>
8
#include <err.h>
9

    
10
int s;
11

    
12
void
13
read_dgram(int sig)
14
{
15
        uint8_t buf[2048];
16
        struct sockaddr_in sin = {0};
17
        ssize_t len;
18
        socklen_t solen = sizeof (sin);
19

    
20
        if (sig != SIGPOLL)
21
                err(-1, "WTF, sig is %d", sig);
22

    
23
        len = recvfrom(s, buf, 2048, 0, (struct sockaddr *)&sin, &solen);
24
        if (len == -1)
25
                err(-1, "recvfrom");
26

    
27
        printf("Received %d bytes\n", len);
28
}
29

    
30
main()
31
{
32
        struct sockaddr_in sin = {AF_INET};
33
        pid_t pid = getpid();
34
        int on = 1;
35

    
36
        s = socket(AF_INET, SOCK_DGRAM, 0);
37
        if (s == -1)
38
                err(-1, "socket");
39

    
40
        if (ioctl(s, SIOCSPGRP, &pid) == -1)
41
                err(-1, "ioctl(PGRP)");
42
        if (ioctl(s, FIOASYNC, &on) == -1)
43
                err(-1, "ioctl(PGRP)");
44

    
45
        sigset(SIGPOLL, read_dgram);
46
        sin.sin_port = htons(2112);
47
        if (bind(s, (struct sockaddr *)&sin, sizeof (sin)) == -1)
48
                err(-1, "bind");
49

    
50
        while (1)
51
                sleep(10);
52
}