这里以简单的一段程序为例:
/*
* daemon.c
*
* Created on: 2012-7-13
* Author: liwei.cai
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int i, fd;
char *buf ="This is a Daemon\n";
pid = fork(); //第一步 创建子进程,父进程退出
if (pid < 0)
{
printf("Error fork\n");
exit(1);
}
else if (pid >0)
{
exit(0);// 父进程退出
}
setsid();//第二步 在子进程中创建新会话
chdir("/");//第三步 改变当前目录为根目录
umask(0);//第四步 重设文件权限掩码
for(i = 0; i < getdtablesize(); i++) //第五步 关闭文件描述符
{
close(i);
}
//这时候已经创建完成守护进程,以下开始正式进入守护进程工作
while(1)
{
if((fd = open("/tmp/daemon.log",
O_CREAT|O_WRONLY|O_APPEND,0600)) < 0)
{
printf("Open file error\n");
exit(1);
}
write(fd, buf, strlen(buf)+1);
close(fd);
sleep(10);
}
exit(0);
}
你可以理解包好了这么多的头文件,其实不是头文件也一样,为简单起见,我就没有了搞那么复杂了,这是创建一个简单的守护进程的例子。
(1)将你该程序的相关文件,放在同一个目录下;
(2)终端进入该目录,输入命令:autoscan 此时会生成configure.scan,修改相关内容,并重名为:configure.in;
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.68])
AC_INIT(daemon, 1.0, cailiwei712@163.com)
AM_INIT_AUTOMAKE(daemon,1.0) #此行为黑体
AC_CONFIG_SRCDIR([daemon.c])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CC
# Checks for libraries.
# Checks for header files.
AC_CHECK_HEADERS([fcntl.h stdlib.h string.h syslog.h unistd.h])
AC_CONFIG_FILES([makefile]) #此行为黑体
# Checks for typedefs, structures, and compiler characteristics.
AC_TYPE_PID_T
# Checks for library functions.
AC_FUNC_FORK
AC_OUTPUT
黑体部分是自己添加上去的。
AM_INIT_AUTOMAKE的第一个参数是软件名,第二个是版本号,三个是bug处理地址。
(3)使用命令:aclocal生成aclocal.m4
(4)使用命令:autoconf生成configure
(5)使用命令:autoheader生成config.h.in
(6)新建并编辑makefile.am
/****makefile.am****/
AUTOMAKE_OPTIONS=foreign //foreign(只检测必须的)、gnu(默认的)、gnits为软件等级。
bin_PROGRAMS= daemon // 产生药执行的文件名
daemon_SOURCES= daemon.c //执行程序所需要的原始文件(是自己建的) 有多少写多少
(7)使用命令:automake生成makefile.in
(8)使用命令:configure 生成makefile
现在基本上就生成好了makefile文件,要检测是否正确,只要输入:make命令就行了。此时可以在当前目录运行该可执行文件了。
使用:make install 可以将程序安装到系统中。make dist 生成压缩包,就可以发布了。make clean 也可以用...你现在就尽情的试试看.