您的位置:首页 > 其它

关于守护进程的解析

2017-08-11 17:22 141 查看
1

以下是守护进程的创建用法,创建过后你会发现 ps -ef|grep a.out ,抓一下过后你会发现用

root     14203     1 99 16:57 ?        00:00:05 ./a.out

root     14205 10818  0 16:57 pts/1    00:00:00 grep a.out


说明有一个子进程已经脱离终端到后台运行了,此时你如果用gcc 编译一下,你会发现

/usr/bin/ld: cannot open output file a.out: Permission denied

collect2: ld 返回 1


解决的办法上面已经说过了

#include <unistd.h>

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

#include <fcntl.h>

#include <stdlib.h>

int daemon(int nochdir, int noclose)

{
pid_t pid =fork ();//创建子进程,关闭父进程
if (pid >0)
{
exit(0);
}
else if (pid <0)
{
return -1;
}

// 设置文件的掩码,mode &-umask
umask(0);
// 设置新的会话;脱离当前会话和终端的控制
if (setsid()<0)
{
return -1;
}

if (nochdir==0)//改变当前的工作目录
{
if(chdir("/")<0)
{
return -1;
}
}
// 标准的输入,关闭标准输出,标准错误
close (STDIN_FILENO);//0

    close (STDOUT_FILENO);// 1
close (STDERR_FILENO);// 2

if (noclose==0)// 重定向标准输入,关闭标准输出,标准错误
{
open("/dev/null",O_RDONLY);

         open("/dev/null",O_RDWR);
open("/dev/null",O_RDWR);
}

return 0;

}

int main()

{
daemon(0,0);
while (1);
return 0;

}

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