linux 一個簡單守護進程執行個體

來源:互聯網
上載者:User

/*守護進程執行個體子*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define MAXFILE 65535

int main()
{
    pid_t pc;
    int i,fd,len;
    char *buf="this is a dameon /n";
    len = strlen(buf);
    pc =fork();     //建立一個進程用來做守護進程
    if(pc<0)
        {
            printf("error fork /n");
            exit(1);
        }
    else if(pc>0)
        exit(0);    //結束父進程
    setsid();       //使子進程獨立1.擺脫原會話控制 2.擺脫原進程組的控制 3.擺脫控制中端的控制
    chdir("/");     //改變當前工作目錄,這也是為了擺脫父進程的影響
    umask(0);       //重設檔案許可權掩碼
    for(i=0;i<MAXFILE;i++)  //關閉檔案描述符(常說的輸入,輸出,報錯3個檔案),
                            //因為守護進程要失去了對所屬的控制終端的聯絡,這三個檔案要關閉
        close(i);
    while(1)
        {
            if((fd=open("/tmp/dameon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0)
                {
                    printf("open file err /n");
                    exit(0);
                }
            write(fd,buf,len+1);
            close(fd);
            sleep(10);
        }
}

聯繫我們

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