epoll的tcp并发服务器

#include "head.h"
#define ERR_MSG(msg) do{fprintf(stderr,"line:%d",__LINE__);perror(msg);}while(0)
#define IP "192.168.250.100"
#define PORT 6666
int deal_cli_msg(int newfd,struct sockaddr_in cin);
 
//回收僵尸进程
void handler(int sig)
{
    while(waitpid(-1,NULL,WNOHANG)>0);
}
 
int main(int argc,const char * argv[])
{
    //捕获17号 SIGCHLD信号,回收僵尸进程
    __sighandler_t s=signal(17,handler);
    if(SIG_ERR==s)
    {
        ERR_MSG("signal");
        return -1;
    }
    //创建流式套接字
    int sfd=socket(AF_INET,SOCK_STREAM,0);
    if(sfd<0)
    {
        ERR_MSG("socket");
        return -1;
    }
    printf("sfd=%d\n",sfd);
    //允许端口快速重用
    int reuse=1;
    if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)
    {
        ERR_MSG("setsockopt");
        return -1;
    }
    printf("允许端口快速重用成功\n");
 
    //填充地址信息结构体
    struct sockaddr_in sin;
    sin.sin_family =AF_INET;
    sin.sin_port =htons(PORT);
    sin.sin_addr.s_addr=inet_addr(IP);
    //将ip和端口绑定到套接字上
    if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
    {
        ERR_MSG("bind");
        return -1;
    }
    printf("ip绑定套接字成功__%d__\n",__LINE__);
    //将套接字设置为可监听状态
    if(listen(sfd,128)<0)
    {
        ERR_MSG("listen");
        return -1;
    }
    printf("将套接字设置为可监听状态成功__%d__\n",__LINE__);
    //存储连接成功的客户端地址信息
    struct sockaddr_in cin;
    socklen_t addrlen =sizeof(cin);
    int newfd=-1;
    //用epoll来接收和发送
     int epfd, i, fd, ret;
    struct epoll_event event;
    struct epoll_event revents[10];
    char buf[128] = {0};
    // 1.创建epoll
    if ((epfd = epoll_create(10)) == -1)
        PRINT_ERR("epoll create error");
 
    for (i = 1; i < argc; i++)
    {
        if ((fd = open(argv[i], O_RDWR)) == -1)
            PRINT_ERR("open file error");
 
        event.events = EPOLLIN;
        event.data.fd = fd;
        // 2.向epoll中添加想要监听的事件
        if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event))
            PRINT_ERR("epoll ctl error");
    }
 
    while (1)
    {
        // 3.阻塞等待事件准备好
        ret = epoll_wait(epfd, revents, 10, -1);
        if (ret == -1)
        {
            PRINT_ERR("epoll wait error");
        }
 
        for (i = 0; i < ret; i++)
        {
            if (revents[i].events & EPOLLIN)
            {
                read(revents[i].data.fd, buf, sizeof(buf));
                printf("fd = %d,buf = %s\n", revents[i].data.fd, buf);
            }
        }
    }
	//关闭进程的所有的文件描述符
    for(i=0;i<getdtablesize();i++){
        close(i);
    }
    return 0;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值