侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Linux网络编程wait()和waitpid()的讲解

linux  /  管理员 发布于 7年前   183

客户端断开连接后,服务器端存在大量僵尸进程。这是由于服务器子进程终止后,发送SIGCHLD信号给父进程,而父进程默认忽略了该信号。为避免僵尸进程的产生,无论我们什么时候创建子进程时,主进程都需要等待子进程返回,以便对子进程进行清理。为此,我们在服务器程序中添加SIGCHLD信号处理函数。

复制代码代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
#define SERV_PORT 1113
#define LISTENQ 32
#define MAXLINE 1024
/***连接处理函数***/
void str_echo(int fd);
void
sig_chld(int signo)
{
pid_t pid;
int stat;
pid = wait(&stat);//获取子进程进程号
printf("child %d terminated\n", pid);
return;
}
int
main(int argc, char *argv[]){
int listenfd,connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in servaddr;
struct sockaddr_in cliaddr;
//struct sockaddr_in servaddr;
//struct sockaddr_in cliaddr;
if((listenfd = socket(AF_INET, SOCK_STREAM,0))==-1){
fprintf(stderr,"Socket error:%s\n\a",strerror(errno));
exit(1);
}
/* 服务器端填充 sockaddr结构*/
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl (INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
signal(SIGCHLD,sig_chld);//处理SIGCHLD信号
/* 捆绑listenfd描述符 */
if(bind(listenfd,(struct sockaddr*)(&servaddr),sizeof(struct sockaddr))==-1){
fprintf(stderr,"Bind error:%s\n\a",strerror(errno));
exit(1);
}
/* 监听listenfd描述符*/
if(listen(listenfd,5)==-1){
fprintf(stderr,"Listen error:%s\n\a",strerror(errno));
exit(1);
}
for ( ; ; ) {
clilen = sizeof(cliaddr);
/* 服务器阻塞,直到客户程序建立连接 */
if((connfd=accept(listenfd,(struct sockaddr*)(&cliaddr),&clilen))<0){
/*当一个子进程终止时,执行信号处理函数sig_chld,
而该函数返回时,accept系统调用可能返回一个EINTR错误,
有些内核会自动重启被中断的系统调用,为便于移植,将考虑对EINTR的处理*/
if(errno==EINTR)
continue;
fprintf(stderr,"Accept error:%s\n\a",strerror(errno));
exit(1);
}
//有客户端建立了连接后
if ( (childpid = fork()) == 0) { /*子进程*/
close(listenfd); /* 关闭监听套接字*/
str_echo(connfd); /*处理该客户端的请求*/
exit (0);
}
close(connfd);/*父进程关闭连接套接字,继续等待其他连接的到来*/
}
}
void str_echo(int sockfd){
ssize_t n;
char buf[MAXLINE];
again:
while ( (n = read(sockfd, buf, MAXLINE)) > 0)
write(sockfd, buf, n);
if (n < 0 && errno == EINTR)//被中断,重入
goto again;
else if (n < 0){//出错
fprintf(stderr,"read error:%s\n\a",strerror(errno));
exit(1);
}
}

修改代码后,当客户端断开连接后,服务器端父进程收到子进程的SIGCHLD信号后,会执行sig_chld函数,对子进程进行了清理,便不会再出现僵尸进程。此时,一个客户端主动断开连接后,服务器端会输出类似如下信息:
child 12306 terminated
wait和waitpid
上述程序中sig_chld函数,我们使用了wait()来清除终止的子进程。还有一个类似的函数wait_pid。我们先来看看这两个函数原型:
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
官方描述:All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about  the  child  whose state  has changed.  A state change is considered to be: the child ter minated; the child was stopped by a signal; or the child was resumed by a  signal.  In the case of a terminated child, performing a wait allows the system to release the resources associated with  the  child; if  a wait  is not performed, then the terminated child remains in a "zombie" state (see NOTES below).
关于wait和waitpid两者的区别与联系:
The wait() system call suspends execution of the calling process  until one  of  its children terminates.  The call wait(&status) is equivalent to:
waitpid(-1, &status, 0);
The waitpid() system call suspends execution  of  the  calling  process until a child specified by pid argument has changed state.  By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument, as described below.
  也就是说,wait()系统调用会挂起调用进程,直到它的任意一个子进程终止。调用wait(&status)的效果跟调用waitpid(-1, &status, 0)的效果是一样一样的。
  waitpid()会挂起调用进程,直到参数pid指定的进程状态改变,默认情况下,waitpid() 只等待子进程的终止状态。如果需要,可以通过设置options的值,来处理非终止状态的情况。比如:
The value of options is an OR of zero or more  of  the  following  constants:
 WNOHANG     return immediately if no child has exited.
 WUNTRACED   also  return  if  a  child  has stopped (but not traced via ptrace(2)).  Status for traced children which have  stopped is provided even if this option is not specified.
WCONTINUED (since Linux 2.6.10)also return if a stopped child has been resumed by delivery of SIGCONT.
等等一下非终止状态。
 现在来通过实例看看wait()和waitpid()的区别。
通过修改客户端程序,在客户端程序中一次性建立5个套接字连接到服务器,状态如下图所示(附代码):





复制代码代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
#define SERV_PORT 1113
#define MAXLINE 1024
void str_cli(FILE *fp, int sockfd);
int
main(int argc, char **argv)
{
int i,sockfd[5];
struct sockaddr_in servaddr;
if (argc != 2){
fprintf(stderr,"usage: tcpcli <IPaddress>\n\a");
exit(0);
}
for(i=0;i<5;++i){//与服务器建立五个连接,以使得服务器创建5个子进程
if((sockfd[i]=socket(AF_INET,SOCK_STREAM,0))==-1){
fprintf(stderr,"Socket error:%s\n\a",strerror(errno));
exit(1);
}

/* 客户程序填充服务端的资料*/
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
fprintf(stderr,"inet_pton Error:%s\a\n",strerror(errno));
exit(1);
}
/* 客户程序发起连接请求*/
if(connect(sockfd[i],(struct sockaddr *)(&servaddr),sizeof(struct sockaddr))==-1){
fprintf(stderr,"connect Error:%s\a\n",strerror(errno));
exit(1);
}
}
str_cli(stdin, sockfd[0]);/*仅用第一个套接字与服务器交互*/
exit(0);
}
void
str_cli(FILE *fp, int sockfd)
{
int nbytes=0;
char sendline[MAXLINE],recvline[MAXLINE];
while (fgets(sendline, MAXLINE, fp) != NULL){//从标准输入中读取一行
write(sockfd, sendline, strlen(sendline));//将该行发送给服务器
if ((nbytes=read(sockfd, recvline, MAXLINE)) == 0){//从sockfd读取从服务器发来的数据
fprintf(stderr,"str_cli: server terminated prematurely\n");
exit(1);
}
recvline[nbytes]='\0';
fputs(recvline, stdout);
}
}

当客户终止时,所以打开的描述子均由内核自动关闭,因此5个连接基本在同一时刻发生,相当于同时引发了5个FIN发往服务器,这会导致5个服务器子进程基本在同一时刻终止,从而导致5个SIGCHLD信号几乎同时递送给服务器父进程,示意图如下所示:

也就是说,几乎在同一时刻,递送5个SIGCHLD信号给父进程,这又会僵尸进程进程的出现。因为unix一般不对信号进行排队,这就导致了5个SIGCHLD递交上去,只执行了一次sig_chld函数,剩下四个子进程便成为了僵尸进程。对于这种情况,正确的做法是调用waitpid(),而不是wait()。
因此,我们最后的服务器端代码中的信号处理函数做一点小改动,改成如下:

复制代码代码如下:
void
sig_chld(int signo)
{
pid_t pid;
int stat;
while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0)
printf("child %d terminated\n", pid);
return;
}

至此,我们解决了网络编程中可能遇到的三类情况:
1.当派生子进程时,必须捕获SIGCHLD信号。代码片段:signal(SIGCHLD,sig_chld);
2.当捕获信号时,必须处理被中断的系统调用。代码片段:if(errno==EINTR) continue;
3.SIGCHLD信号处理函数必须编写正确,以防出现僵尸进程。代码片段:while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0)


  • 上一条:
    用date命令修改Linux系统的时间为什么无效?怎么才能正确显示
    下一条:
    Linux网络编程使用多进程实现服务器并发访问
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在Linux系统中使用Iptables实现流量转发功能流程步骤(0个评论)
    • vim学习笔记-入门级需要了解的一些快捷键(0个评论)
    • 在centos7系统中实现分区并格式化挂载一块硬盘到/data目录流程步骤(0个评论)
    • 在Linux系统种查看某一个进程所占用的内存命令(0个评论)
    • Linux中grep命令中的10种高级用法浅析(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-11
    • 2017-07
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-03
    • 2022-04
    • 2022-08
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-06
    • 2023-07
    • 2023-10
    • 2023-12
    • 2024-01
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客