lighttpd1.4.16 主程式邏輯 (一)觀察者和工作者
阿新 • • 發佈:2019-02-17
一、觀察者和工作者
對程序進行管理。父程序作為觀察者,負責啟動和監聽工作者程序
程式檔案:server.c
行:970~996
原始碼:
程式碼1
- /* start watcher and workers */
- num_childs = srv->srvconf.max_worker;
- if (num_childs > 0) {
- int child = 0;
- while (!child && !srv_shutdown) {
- if (num_childs > 0) {
- switch (fork()) {
- case -1:
- return -1;
- case 0:
- child = 1;
- break;
- default:
- num_childs--;
- break;
- }
- } else {
- int status;
- /* ignore EINTR */
- if (-1 != wait(&status)) num_childs++;
- }
- }
- if (srv_shutdown) {
- kill(0, SIGTERM);
- }
- if (!child) return
- }
抽取解析
以下程式碼1-1將程式碼1抽取出來
程式碼1-1
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- /**
- * 程序管理
- * 程序的開啟和程序的維護,包括關閉
- *
- * */
- int main(int argc,char** argv)
- {
- //是否子程序的標誌
- int is_child=0;
- //服務退出標誌
- int is_server_close=0;
- int ppid=0;
- int cid=0;
- //最大程序數
- int max_child_count=5;
- //is_child=0用來判斷是否父程序,只有父程序才能進入此迴圈
- while(0==is_child && 0==is_server_close)//父程序執行此程式碼
- {
- //是否還有程序要建立
- if(max_child_count>0)
- {
- cid=fork();
- switch(cid)
- {
- //錯誤
- case -1:
- {
- printf("fork process=%d error/n",max_child_count);
- return -1;
- }
- //子程序
- case 0:
- {
- is_child=1;
- break;
- }
- //父程序
- default:
- {
- //建立子程序成功
- //程序數減少
- --max_child_count;
- printf("sub process id =%d/n",cid);
- printf("parent printf is_child value:%d/n",is_child);
- break;
- }
- }
- //所有程序都建立完畢
- }else
- {
- int status;
- //開始阻塞等待子程序是否結束
- if(-1!=wait(&status))
- {
- //結束,將程序數累加1,使迴圈可以重新啟動新的程序
- max_child_count++;
- }
- }
- }
- //父程序結束維護子程序後的處理
- if(is_child==0)
- {
- printf("parent end/n");
- return 0;
- //子程序業務處理
- }else{
- sleep(5);
- printf("child id=%d end/n",cid);
- return 0;
- }
- }