您的位置:首页 > 运维架构 > Linux

linux下创建后台守护进程实例

2013-01-25 15:23 357 查看
步骤:

1. 父进程通过fork函数创建一个子进程,然后父进程退出

2. 子进程中使用setsid函数创建一个新的会话

3. 切换进程的工作目录到根目录

4. 设置进程的umask为0

5. 关闭不需要的文件操作符

实例代码:

#include <stdio.h>

#incude <stdlib.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/select.h>

#include <sys/time.h>

int main(int argc, char* argc)

{

pid_t pid, sid;

// 创建一个子进程

pid = fork();

if (pid < 0)

{

perror("fork");

exit(EXIT_FAILURE);

}

if (pid > 0)

{

//主进程退出

exit(EXIT_SUCCESS);

}

// 子进程中,创建一个新的会话

if ((sid = setsid()) < 0)

{

perror("setsid");

exit(EXIT_FAILURE);

}

// 重新设置文件权限模式

umask(0);

//关闭从主进程中继承来的不需要的输入输出描述符

close(STDIN_FILENO);

close(STDOUT_FILENO);

close(STDERR_FILENO);

// 实现守护进程需完成的工作

int i = 0;

//struct timeval

//{

// long tv_sec; //seconds

// long tv_usec; // microseconds

//};

struct timeval;

timeval.tv_sec = 1;

timeval.tv_usec = 0;

while(i < 10000)

{

printf("To do your work\n");

select(0, NULL, NULL, NULL, &timeval);

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: