Daemon函数的用法函数
说明:spa
让一个程序后台运行。.net
原型:code
- #include <unistd.h>
-
- int daemon(int nochdir, int noclose);
blog
参数:进程
当 nochdir为零时,当前目录变为根目录,不然不变;ip
当 noclose为零时,标准输入、标准输出和错误输出重导向为/dev/null,也就是不输出任何信 息,不然照样输出。get
返回值:原型
deamon()调用了fork(),若是fork成功,那么父进程就调用_exit(2)退出,因此看到的错误信息 所有是子进程产生的。若是成功函数返回0,不然返回-1并设置errno。string
示例:
- #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函数运行完毕后自杀,之后的休眠和打印所有是子进程来运行。
能够修改daemon函数的参数来查看效果。
能够去掉daemon一句,用./a.out&来验证效果。