deamon函数是使当前程序切换到后台运行。
函数原型:
#include <unistd.h>
int daemon(int nochdir, int noclose);
参数说明:
nochdir:为零时,当前目录变为根目录,否则不变;
noclose:为零时,标准输入、标准输出和错误输出重导向为/dev/null,也就是不输出任何信 息,否则照样输出。
返回值:
deamon()调用了fork(),如果fork成功,那么父进程就调用_exit(2)退出,所以看到的错误信息 全部是子进程产生的。如果成功函数返回0,否则返回-1并设置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函数运行完毕后退出,后续的功能(休眠和打印)全部是子进程来执行。