以下例子是創建一個守護進程,間隔5s在/tmp目錄下寫文件
#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <fcntl.h>#include <sys/time.h>#include <sys/resource.h>#include <string.h>#include <time.h>void daemonize(){ //1. 創建一個子進程,父進程退出,主要就是為setsid做準備 pid_t pid; pid = fork(); if (pid < 0) { PRintf("fork error/n"); return ; } else if (pid > 0) { exit(0); } //2. 調用setsid創建新會話, 如果不創建新會話的話。原來依附在父進程的會話是終端bash創建的, //這樣在關閉那個終端sh后, 整個會話就會退出 setsid(); //3. 改變當前目錄, 只要任意可以隨意訪問的目錄,因為不同的目錄掛載有可能 //掛載在不同的文件系統上,為了保證守護進程開機啟動不依賴對應的文件系統, //默認將它改變到/目錄上 if (chdir("/") < 0) { printf("change dir to '/' error/n"); return; } //4. 設置文件掩碼, 以免在守護進程運行過程中新創建的文件不適合對應權限 umask(0); //5. 關閉對應的文件描述符 struct rlimit rlim; if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) { perror("getrlimit"); return ; } int i = 0; for (; i < rlim.rlim_cur; ++i) { close(i); } //6. 工作代碼 int fd = open("/tmp/test.log", O_CREAT | O_RDWR | O_APPEND, 0644); while(1) { //char *ctime(const time_t *timep); time_t tt = time(NULL); char *ts = ctime(&tt); write(fd, ts, strlen(ts)); sleep(5); } close(fd);}int main(int argc, char **argv){ daemonize(); return 0;}
新聞熱點
疑難解答