#include#include #include #include #include #include #include #include #include #include #include #define SRV_PORT 9999 int main(int argc,char **argv){ int lfd,cfd; pid_t pid; struct sockaddr_in serv_addr,cli_addr; socklen_t cli_addr_len; char buf[BUFSIZE]; int n,i; bzero(&serv_addr,sizeof(sercv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); serv_addr.sin_port=htons(SERV_PORT); lfd=socket(AF_INET,SOCK_STREAM,0); Bind(lfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); Listen(lfd,128); cli_addr_len=sizeof(cli_addr); while(1){ cfd=Accept(lfd,(struct sockaddr*)&cli_addr,sizeof(cli_addr)); pid=fork(); if(pid<0){ perror("fork error"); }else if(pid==0){ close(lfd); break; }else{ close(cfd); continue; } } if(pid==0){ for(;;){ n=Read(cfd,buf,sizeof(buf)); if(n==0){ close(cfd); exit(1); } for(i=0;i 会出现僵尸进程,父进程由于阻塞所以没能回收子进程。利用信号来解决:
这样,当子进程退出时,父进程收到信号,就会去回收子进程了,不会出现僵尸进程#include#include #include #include #include #include #include #include #include #include #include #include #define SRV_PORT 9999 void catch_child(int signum){ while((waitpid(0,NULL,WNOHANG))>0); return; } int main(int argc,char **argv){ int lfd,cfd; pid_t pid; struct sockaddr_in serv_addr,cli_addr; socklen_t cli_addr_len; char buf[BUFSIZE]; int n,i; bzero(&serv_addr,sizeof(sercv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); serv_addr.sin_port=htons(SERV_PORT); lfd=socket(AF_INET,SOCK_STREAM,0); Bind(lfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); Listen(lfd,128); cli_addr_len=sizeof(cli_addr); while(1){ cfd=Accept(lfd,(struct sockaddr*)&cli_addr,sizeof(cli_addr)); pid=fork(); if(pid<0){ perror("fork error"); }else if(pid==0){ close(lfd); break; }else{ struct sigaction act; act.sa_handler=catch_child; sigemptyset(&act.sa_mask); act.sa_flags=0; n=sigaction(SIGCHILD,&act,NULL); if(n!=0){ perror("sigaction error"); } close(cfd); continue; } } if(pid==0){ for(;;){ n=Read(cfd,buf,sizeof(buf)); if(n==0){ close(cfd); exit(1); } for(i=0;i 欢迎分享,转载请注明来源:内存溢出
服务器客户端多进程
赞
(0)
打赏
微信扫一扫
支付宝扫一扫
【满满干货内容】Python I 超实用的50段简短代码实例~新手福利!
上一篇
2022-11-07
(2)python
下一篇
2022-11-07
评论列表(0条)