歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux管理 >> Linux網絡 >> Linux網絡編程wait()和waitpid()的講解

Linux網絡編程wait()和waitpid()的講解

日期:2017/3/1 18:02:11   编辑:Linux網絡
客戶端斷開連接後,服務器端存在大量僵屍進程。這是由於服務器子進程終止後,發送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)
Copyright © Linux教程網 All Rights Reserved