linux deamon函数使用方法说明
来源:互联网 发布:夏普电视音频输出端口 编辑:程序博客网 时间:2024/05/16 16:09
转自http://blog.chinaunix.net/uid-20196318-id-94985.html
其实,linux提供了daemon函数用于创建守护进程
#include
int daemon(int nochdir, int noclose);
1. daemon()函数主要用于希望脱离控制台,以守护进程形式在后台运行的程序。
2. 当nochdir为0时,daemon将更改进城的根目录为root(“/”)。
3. 当noclose为0是,daemon将进城的STDIN, STDOUT, STDERR都重定向到/dev/null。
daemon的实现大致如下:
int daemon( int nochdir, int noclose )
{
pid_t pid;
if ( !nochdir && chdir("/") != 0 ) //如果nochdir=0,那么改变到"/"根目录
return -1;
if ( !noclose ) //如果没有noclose标志
{
int fd = open("/dev/null", O_RDWR);
if ( fd < 0 )
return -1;
/* 重定向标准输入、输出、错误 到/dev/null,
键盘的输入将对进程无任何影响,进程的输出也不会输出到终端
*/
dup(fd, 0);
dup(fd, 1);
dup(fd, 2);
close(fd);
}
pid = fork(); //创建子进程.
if (pid < 0) //失败
return -1;
if (pid > 0)
_exit(0); //返回执行的是父进程,那么父进程退出,让子进程变成真正的孤儿进程.
//创建的 daemon子进程执行到这里了
if ( setsid() < 0 ) //创建新的会话,并使得子进程成为新会话的领头进程
return -1;
return 0; //成功创建daemon子进程
}
使用实例:
int main()
{
daemon(1, 1); //参数根据需求确定
/* 在这里添加你需要在后台做的工作代码 */
}
如何杀死这样的进程:
通过ps+grep找到对应的后台进程,使用kill命令将进程杀死;也可创建shell脚本对进程的启动、关闭、重启进行自动管理
- linux deamon函数使用方法说明
- Linux C/C++ 找不到deamon函数声明的解决方法
- Linux Deamon编程方法
- Linux Deamon编程方法
- Linux Deamon编程方法
- Linux Deamon编程方法
- Linux Deamon编程方法
- linux服务deamon
- linux/Android LED deamon
- linux安装deamon
- deamon
- linux下的deamon进程
- linux下的deamon进程
- linux下的deamon进程
- linux下的deamon进程
- EntityManager使用方法 API 函数说明
- Mongodb C++ Deamon 及API说明
- Linux Deamon(守护进程)实现方法
- 第一个ssm项目
- 超酷超炫特效动画
- MQ消息架构设计一(到底什么时候该使用MQ?)
- leetcode 160. Intersection of Two Linked Lists
- (三)u-boot启动流程分析(C语言部分board_f.c)
- linux deamon函数使用方法说明
- 矩阵的物理意义
- Building for UN UVA
- Linux Jenkins 安装
- 爬虫之窃取网络小说(2,多线程爬虫)-yellowcong
- node更新与npm库更新
- IOS开发笔记--视频录制
- IBM系列软件“安装”阶段出错问题的解决
- swoole的安装