|
|
发表于 2005-8-20 00:42:21
|
显示全部楼层
modified version
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <errno.h>
- #include <string.h>
- #include <signal.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <sys/ioctl.h>
- #define MAX_LENTH 1500
- static int nqueue = 0;
- void sigio_handler(int signum)
- {
- if (signum = SIGIO)
- nqueue++;
- return;
- }
- static recv_buf[MAX_LENTH];
- int main(int argc, char *argv[])
- {
- int sockfd, on = 1;
- struct sigaction action;
- sigset_t newmask, oldmask;
- struct sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = INADDR_ANY;
- addr.sin_port = htons(50001);
- if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
- perror("Create socket failed");
- exit(-1);
- }
- if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
- perror("Bind socket failed");
- exit(-1);
- }
- memset(&action, 0, sizeof(action));
- action.sa_handler = sigio_handler;
- action.sa_flags = 0;
- sigaction(SIGIO, &action, NULL);
- if (fcntl(sockfd, F_SETOWN, getpid()) == -1) {
- perror("Fcntl F_SETOWN failed");
- exit(-1);
- }
- if (ioctl(sockfd, FIOASYNC, &on) == -1) {
- perror("Ioctl FIOASYNC failed");
- exit(-1);
- }
- sigemptyset(&oldmask);
- sigemptyset(&newmask);
- sigaddset(&newmask, SIGIO);
- while (1) {
- int len;
- sigprocmask(SIG_BLOCK, &newmask, &oldmask);
- while (nqueue == 0)
- sigsuspend(&oldmask);
- len = recv(sockfd, recv_buf, MAX_LENTH, MSG_DONTWAIT);
- if (len == -1 && errno == EAGAIN)
- nqueue = 0;
- sigprocmask(SIG_SETMASK, &oldmask, NULL);
- if (len >= 0)
- printf("recv %d byte(s)\n", len);
- }
- }
复制代码 |
|