Linux網絡編程(三)

Linux網絡編程(三) wait()仍是waitpid()編程

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函數,對子進程進行了清理,便不會再出現殭屍進程。此時,一個客戶端主動斷開鏈接後,服務器端會輸出相似以下信息:socket

child 12306 terminated

wait和waitpid
上述程序中sig_chld函數,咱們使用了wait()來清除終止的子進程。還有一個相似的函數wait_pid。咱們先來看看這兩個函數原型:
tcp

pid_t wait(int *status);ide

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).ui

關於wait和waitpid二者的區別與聯繫:this

The wait() system call suspends execution of the calling process  until one  of  its children terminates.  The call wait(&status) is equivalent to:spa

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)


next....

相關文章
相關標籤/搜索