您的位置:首页 > 编程语言

一个小并发服务器的代码优化

2014-03-26 15:19 288 查看
while(1){

        //服务器阻塞,直到客户程序建立连接

        sin_size=sizeof(struct sockaddr_in);

        if ((new_fd=accept(sockfd,(struct sockaddr *)(&client_addr),(socklen_t *)&sin_size))==-1)

        {

                fprintf(stderr,"Accept error:%s\n\a",strerror(errno));

                exit(1);

  }

        fprintf(stdout,"Server get connection from %s\n", inet_ntoa(client_addr.sin_addr));

  //子进程处理接入的TCP连接

  //父进程继续监听

  pid_t pid = fork();

  if (pid < 0){

   perror("call to fork");

   exit(1);

  }

  else if (0 == pid){

   while(1){

    //主动上传变化的数据报文

    //dataup_104frame(new_fd);

/****************************************************************/

**对于非正常断开的连接,子进程还不能够退出,导致子进程越来越多

**getsockopt函数是否可以获得socket状态???

    //检查TCP连接状态,断开已中断的连接

    //处理接收到的104报文

    if(!new_fd){

     exit(1);

    }

    if((recbytes=recv(new_fd, buf, 1024, 0)) <= 0){

     perror("call to recv");

     close(new_fd);

     exit(1);

    }

/*****************************************************************/

    process_104frame(new_fd, buf, recbytes);

   }

  }

  else{

   close(new_fd);

   fprintf(stdout, "IEC104 server continues listening\n\r");

  }

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐