- 论坛徽章:
- 0
|
/** SIGIO server end **/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SA struct sockaddr
#define PORT 9877
#define BUFFSIZE 1024
static int sockfd; /** UDP socket descriptor **/
void sig_io(int signo); /** SIGIO handler **/
void err_sys(const char *errmsg);
int main(int argc, char **argv)
{
struct sockaddr_in serv;
int flag;
struct sigaction act;
/** create UDP scoket **/
if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
err_sys("socket error");
/** install SIGIO handler **/
act.sa_handler = sig_io;
if (sigemptyset(&act.sa_mask) == -1)
err_sys("sigemptyset error");
act.sa_flags = 0;
if (sigaction(SIGIO, &act, NULL) == -1)
err_sys("sigaction error");
/** set socket own **/
if (fcntl(sockfd, F_SETOWN, getpid()) == -1)
err_sys("fcntl error");
/** open O_ASYNC flag **/
if ((flag = fcntl(sockfd, F_GETFL, 0)) == -1)
err_sys("fcntl error");
else if (fcntl(sockfd, F_SETFL, flag | O_ASYNC) == -1)
err_sys("fcntl error");
/** initialize socket address structure **/
bzero(&serv, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port = htons(PORT);
if (bind(sockfd, (SA *) &serv, sizeof(serv)) == -1)
err_sys("bind error");
for (;;)
pause();
exit(0);
}
void sig_io(int signo)
{
char buff[BUFFSIZE];
ssize_t nbytes;
if ((nbytes = recvfrom(sockfd, buff, BUFFSIZE, 0, NULL, NULL)) == -1)
err_sys("recvfrom error");
else if (write(STDOUT_FILENO, buff, nbytes) != nbytes)
err_sys("write error");
}
void err_sys(const char *errmsg)
{
perror(errmsg);
exit(1);
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/30746/showart_238690.html |
|