一個簡單的GNU 守護進程的建立

來源:互聯網
上載者:User

/*********************************************************************
 * Function: Test daemon process
 * Author  : Samson
 * Date    : 11/30/2011
 * Test platform:
 *               GNU Linux version 2.6.29.4
 *               gcc version 4.4.0 20090506 (Red Hat 4.4.0-4) (GCC)
 * *******************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <unistd.h>

int
main()
{
    int frokret, fatherid;
    if((frokret = fork()))
    {
        fatherid = getppid();
        printf("father process is %d fatherid is %d\n", frokret, fatherid);
        exit(0);    
    }
    else if(frokret < 0)
    {
        printf("fork is error\n");
    }
    else
    {
        frokret = getpid();
          setsid();
        fatherid = getppid();
        printf("children getpid  is %d fatherid is %d\n", frokret, fatherid);
        while(1)
        {
            //printf("this is children thread\n");    
        }
    }
    exit(0);

}
當注釋掉://setsid();這行的時候 運行結果為:
[root@UFO test]# ./a.out
father process is 3229 fatherid is 3188
children getpid  is 3229 fatherid is 3228
[root@UFO test]# ps -ef | grep a.out
root      3229     1 99 09:03 pts/3    00:01:05 ./a.out

不注釋掉setsid();行的時候運行結果為:
[root@UFO test]# ./a.out
father process is 3254 fatherid is 3188
children getpid  is 3254 fatherid is 3253
[root@UFO test]# ps -ef | grep a.out
root      3254     1 99 09:05 ?        00:00:56 ./a.out

注意看 ps -ef | grep a.out後的結果中的目前時間的列後的那一列,當注釋掉setsid的時候a.out的父進程為pts/3,也就是當前所開的終端進程,並沒有實現一個守護進程的功能,而當不注釋掉的時候,a.out的父進程為?號,即表示它的父進程為init進程,也就是1號進程。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.