Daemon函數(shù)的用法
說明:
讓一個程序后臺運行。
原型:
- #include <unistd.h>
-
- int daemon(int nochdir, int noclose);
參數(shù):
當 nochdir為零時,當前目錄變?yōu)楦夸洠駝t不變;
當 noclose為零時,標準輸入、標準輸出和錯誤輸出重導(dǎo)向為/dev/null,也就是不輸出任何信 息,否則照樣輸出。
返回值:
deamon()調(diào)用了fork(),如果fork成功,那么父進程就調(diào)用_exit(2)退出,所以看到的錯誤信息 全部是子進程產(chǎn)生的。如果成功函數(shù)返回0,否則返回-1并設(shè)置errno。
示例:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <limits.h>
-
- int main(int argc, char *argv[])
- {
- char strCurPath[PATH_MAX];
-
- if(daemon(1, 1) < 0)
- {
- perror("error daemon.../n");
- exit(1);
- }
- sleep(10);
-
- if(getcwd(strCurPath, PATH_MAX) == NULL)
- {
- perror("error getcwd");
- exit(1);
- }
- printf("%s/n", strCurPath);
- return 0;
- }
假如運行成功,父進程在daemon函數(shù)運行完畢后自殺,以后的休眠和打印全部是子進程來運行。
可以修改daemon函數(shù)的參數(shù)來查看效果。
可以去掉daemon一句,用./a.out&來驗證效果。