Daemon函数的用法

Daemon函数的用法函数

说明:spa

让一个程序后台运行。.net

原型:code

 

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

blog

 

参数:进程

nochdir为零时,当前目录变为根目录,不然不变;ip

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

返回值:原型

deamon()调用了fork(),若是fork成功,那么父进程就调用_exit(2)退出,因此看到的错误信息 所有是子进程产生的。若是成功函数返回0,不然返回-1并设置errnostring

示例:

 

[c-sharp] view plain copy print?
  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&来验证效果。

相关文章
相关标签/搜索