用c++创建一个Linux上的Daemon程序,含SHELL管理脚本(一)

来源:互联网 发布:编程儿童产业 编辑:程序博客网 时间:2024/06/06 03:20

用c++创建一个Linux上的Daemon程序,含SHELL管理脚本(一)


本文提供了一个Daemon程序的简单实例,更多高级应用,请参考:

用c++创建一个Linux上的Daemon程序,含SHELL管理脚本(二)

用c++创建一个Linux上的Daemon程序,含SHELL管理脚本(三)


1、编写代码,命名为simple.c

#include <unistd.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <stdlib.h>

#include <stdio.h>

#include <syslog.h>

#include <singnal.h>

#include <fcntl.h>


#define MAXFD 64


int main(void)

{

pid_t pid=fork();

if (pid > 0)

{

exit(0);

}

else if (pid < 0) 

{

exit(1);

}


setsid();


pid_t pid2 = fork();

if (pid2 > 0)

{

exit(0);

}

else if (pid2 < 0) 

{

exit(1);

}


umask(0);


chdir("/");


for (int i = 0; i < MAXFD; ++i)

{

close(i);

}

close(STDIN_FILENO);


if (open("/dev/null", O_RDWR) != STDIN_FILENO)

{

exit(2);

}

if (dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO)

{

exit(2);

}

if (dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO)

{

exit(2);

}


signal(SIGHUP, SIG_IGN);

signal(SIGCHLD, SID_IGN);

while(1)

{

sleep(1);

}


return 0;

}


2、编译

gcc -Wall -std=c99 - o D_test simple.c

或者

g++ -o D_test simple.c


3、运行

./D_test


4、查看运行状态

ps -A