C程式fork進程導致PHP執行不退出

來源:互聯網
上載者:User

標籤:dir   ram   argc   測試的   table   oca   mask   退出   str   

/********************************************************************* *                C程式fork進程導致PHP執行不退出 * 說明: *     由於測試的GPIO程式需要持續運行,而主進程需要處理其他事務但退出時 * 由於子線程未結束導致PHP系統調用函數不退出,解決辦法是雙重fork(第一次 * fork產生子進程用於kill掉讓第二次fork出的子進程變成孤兒進程),並將最終 * 的子進程轉換為守護進程,從而不影響PHP擷取主進程資料。 * *                                   2017-8-16 深圳 龍華樟坑村 曾劍鋒 ********************************************************************/一、參考文檔:     1. Linux 守護進程的實現        http://alfred-sun.github.io/blog/2015/06/18/daemon-implementation/二、測試daemon Demo:    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <time.h>    #include <unistd.h>    #include <sys/param.h>    #include <sys/types.h>    #include <sys/stat.h>    #include <fcntl.h>        // 守護進程初始化函數    void init_daemon()    {        pid_t pid;        int i = 0;            if ((pid = fork()) == -1) {            printf("Fork error !\n");            exit(1);        }        if (pid != 0) {            exit(0);        // 父進程退出        }            setsid();           // 子進程開啟新會話,並成為會話首進程和組長進程        if ((pid = fork()) == -1) {            printf("Fork error !\n");            exit(-1);        }        if (pid != 0) {            exit(0);        // 結束第一子進程,第二子進程不再是會話首進程        }        chdir("/tmp");      // 改變工作目錄        umask(0);           // 重設檔案掩碼        for (; i < getdtablesize(); ++i) {           close(i);        // 關閉開啟的檔案描述符        }            return;    }        int main(int argc, char *argv[])    {        int fp;        time_t t;        char buf[] = {"This is a daemon:  "};        char *datetime;        int len = 0;        //printf("The NOFILE is: %d\n", NOFILE);        //printf("The tablesize is: %d\n", getdtablesize());        //printf("The pid is: %d\n", getpid());            // 初始化 Daemon 進程        init_daemon();            // 每隔一分鐘記錄運行狀態        while (1) {            if (-1 == (fp = open("/tmp/daemon.log", O_CREAT|O_WRONLY|O_APPEND, 0600))) {              printf("Open file error !\n");              exit(1);            }            len = strlen(buf);            write(fp, buf, len);            t = time(0);            datetime = asctime(localtime(&t));            len = strlen(datetime);            write(fp, datetime, len);            close(fp);            sleep(60);        }            return 0;    }

 

C程式fork進程導致PHP執行不退出

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.