(引)并发网络编程学习之路(三):多线程与进线池
(原)ubuntu 9.10 安装 asio库

(转)LINUX 网络编程之Daemon设计

孔令春 posted @ 2009年10月21日 23:41 in 网络安全 with tags DAEMON , 4932 阅读

引言

通常一个服务端程序是不会在前台运行的,而是作为系统服务在后台运行,并随系统启动而启动。这就是我们常说的Daemon程序,又称为守护进程,这种程序由于没有控制终端是无法与前台交互的,但我们随时可以通过系统日志来查看它的状态。下面将讲述在Linux下编写Daemon程序的步骤,并给出了例子程序。

Daemon设计步骤

Daemon程序设计主要步骤包括:

(1)       程序运行后调用fork,并让父进程退出。子进程获得一个新的进程ID,但继承了父进程的进程组ID

(2)       调用setsid创建一个新的session,使自己成为新session和新进程组的leader,并使进程没有控制终端(tty)

(3)       设置文件创建mask0,避免创建文件时权限的影响。

(4)       关闭不需要的打开文件描述符。因为Daemon程序在后台执行,不需要于终端交互,通常就关闭STDINSTDOUTSTDERR。其它根据实际情况处理。

(5)       Daemon无法输出信息,可以使用SYSLOG或自己的日志系统进行日志处理。(可选)

(6)       编写管理DaemonSHELL脚本,使用serviceDaemon进行管理和监控。(可选)

Daemon程序框架

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>         
#include <netdb.h>                
#include <time.h>
#include <strings.h>              
#include <string.h>
#include <errno.h>

int myprod(int port);
int init_daemon(void);

int main(int argc,char *argv[])
{
	
	if(argc != 2)
	{
		printf("please input ./mytelnetd <port>\n");
		exit(1);
	}
	
	//转入后台
	init_daemon();
	
	//启动服务器
	myprod(atoi(argv[1]));
}

int myprod(int port)
{	
   //你的服务器端程序
}


//初始化后台环境
int init_daemon(void)
{

  pid_t pid;
  int i;

  /* parent exits , child continues */

  if((pid = fork()) < 0)
    return -1;
  else if(pid != 0)
    exit(0);

  setsid(); /* become session leader */


  for(i=0;i< 3 ;++i) /* close STDOUT, STDIN, STDERR, */

    close(i);

  umask(0); /* clear file mode creation mask */

  return 0;

}

 

       程序运行后,前台终端会立即释放,但你可以用ps -e来查看。当然这个程序框架只演示了上面的前4步,下面两步我没看明白,你可以参考原文:http://blog.csdn.net/liuben/archive/2008/03/21/2204418.aspx

Avatar_small
HBSE 10th New Questi 说:
2022年8月18日 02:07

The Haryana Board of School Education's HBSE 10th Model Question Paper was published in 2023. The HBSE 10th New Model Paper 2023, HBSE 10th Question Paper 2023, HBSE 10th Sample Question Paper and Guess Paper 2023, or Bhiwani Board 10th New Question Paper 2023 of the examination are to be released by this board in the month designated for the HBSE 10th class examinations. HBSE 10th New Question Paper 2023 The Haryana Board has made the New Question Paper for the Exams available for download so that students may more easily get ready for the Exams in accordance with the New Model Paper.

Avatar_small
Bihar Bhulekh 说:
2022年10月27日 03:01

Land recording is simplified by the introduction of new advance online systems. The Bihar state government has implemented a simple land record website portal. To help all Bihar citizens access past and previous records. Bihar Bhulekh The Bihar Bhulekh portal is a land record and viewing system launched by the Bihar state government. Bhulekh operates under the Central government National Land Record Modernization Program NLRMP scheme.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter