Daemon函数的用法

来源:互联网 发布:软件自学网 下载 编辑:程序博客网 时间:2024/05/18 02:55

说明:

让一个程序后台运行。

原型:

[c-sharp] view plain copy
  1. #include <unistd.h>  
  2.   
  3. int daemon(int nochdir, int noclose);  

参数:

当 nochdir为零时,当前目录变为根目录,否则不变;

当 noclose为零时,标准输入、标准输出和错误输出重导向为/dev/null,也就是不输出任何信 息,否则照样输出。

返回值:

deamon()调用了fork(),如果fork成功,那么父进程就调用_exit(2)退出,所以看到的错误信息 全部是子进程产生的。如果成功函数返回0,否则返回-1并设置errno

示例:

[c-sharp] view plain copy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <unistd.h>  
  4. #include <fcntl.h>  
  5. #include <limits.h>  
  6.   
  7. int main(int argc, char *argv[])  
  8. {  
  9.     char strCurPath[PATH_MAX];  
  10.   
  11.     if(daemon(1, 1) < 0)  
  12.     {  
  13.         perror("error daemon.../n");  
  14.         exit(1);  
  15.     }  
  16.     sleep(10);  
  17.   
  18.     if(getcwd(strCurPath, PATH_MAX) == NULL)  
  19.     {  
  20.         perror("error getcwd");  
  21.         exit(1);  
  22.     }  
  23.     printf("%s/n", strCurPath);  
  24.     return 0;  
  25. }  

假如运行成功,父进程在daemon函数运行完毕后自杀,以后的休眠和打印全部是子进程来运行。

可以修改daemon函数的参数来查看效果。

可以去掉daemon一句,用./a.out&来验证效果。


转自:http://blog.csdn.net/callmeback/article/details/5884579

0 0
原创粉丝点击