Linux c++(socket网络通信 & 多进程服务器)

 #include <stdio.h>                                                                         
  #include <unistd.h>
  #include <stdlib.h>
  #include <sys/types.h>
  #include <arpa/inet.h>
  #include <string.h>
  #include <ctype.h>
  #include <signal.h>
  #include <sys/wait.h>
  #include <errno.h>
      
void sigCatchFun(int num)
  {   
      pid_t wpid ;
      while((wpid= waitpid(-1,NULL,WNOHANG))>0){
          printf("sig child OK\n");
      }
  }   
      
  int main(int argc,char *argv[])
  {        
      if(argc< 2)
      {    
          printf("eg: ./app port");
          exit(1);
      }    
      struct sockaddr_in serv_addr;
      socklen_t serv_len = sizeof(serv_addr);
      int port = atoi(argv[1]);
      //创建套接字
      int lfd = socket(AF_INET,SOCK_STREAM,0);
      //初始化服务器
      memset(&serv_addr,0,serv_len);
      serv_addr.sin_family=AF_INET;
      serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
      serv_addr.sin_port = htons(port);
      //绑定IP和端口  
      bind(lfd,(struct sockaddr*)&serv_addr,serv_len);
      //设置同时监听的最大个数
      listen(lfd,36);
      printf("Start accept ......\n");
       struct sigaction actobj;
      actobj.sa_flags=0;
      actobj.sa_handler = sigCatchFun;
      sigemptyset(&actobj.sa_mask);
      sigaction(SIGCHLD,&actobj,NULL);
  
      struct sockaddr_in client_addr;
      socklen_t cli_len = sizeof(client_addr);
      while(1)
      {    
          // 父进程接收连接请求                                                              
          int cfd = accept(lfd,(struct sockaddr*)&client_addr,&cli_len);
          if (cfd == -1 && errno == EINTR) {
              cfd = accept(lfd,(struct sockaddr*)&client_addr,&cli_len);
          }
          //创建子进程
          pid_t pid = 0;
          pid=fork();
          if(pid == 0)
          {
              close(lfd);
              while(1)
              {
                  char buf[1024];
                  int len = read(cfd,buf,sizeof(buf));
                  if(len == -1)
                  {
                      perror("read error");
                      exit(2);
                  }else if(len == 0)
                  {
                      printf("客户端已断开连接\n");
                      close(cfd);
                      break;
                  }else{
                      printf("recf buf: %s\n",buf);
                      write(cfd,buf,len);
                  }
              }
              //干掉子进程
              return 0;
          }else if(pid > 0)
                        close(cfd);
          }
      }
      close(lfd);
      return 0;
  }   
上一篇:18.5.2 多线程并发服务器端的实现


下一篇:HITCON training lab 11——bamboobox