/* myapp.c */
/***************************************/
#include <unistd.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* global exit status code */
#define RUN_OK 0
#define CONFIG_ERROR 1
#define FATAL_ERROR 2
/* function declaration */
int read_config(void);
int app_init(void);
void daemonize(void);
int main(int argc, char **argv)
{
FILE *fp;
time_t t;
/* Read the app configuration here if applicable. */
/* If error occurred, return non-zero. */
if (read_config() != RUN_OK)
{
printf("%s: read configuration failuren", argv[0]);
exit(CONFIG_ERROR);
}
/* Initialize application. Any error, return non-zero. */
if (app_init() != RUN_OK)
{
printf("%s: initialization failuren", argv[0]);
exit(FATAL_ERROR);
}
daemonize(); /* Make the application a daemon. */
/* Service logic is placed here. */
while (1)
{
sleep(5); /* Sleep for 5 seconds. In a real application, it could be */
/* waiting for service requests, e.g. waiting on message */
/* queue, etc. */
/* service logic */
if ((fp = fopen("/tmp/myapp.log","a")) != NULL)
{
t = time(0);
fprintf(fp, "myapp is running at %sn",asctime(localtime(&t)));
fclose(fp);
}
else
{
exit(FATAL_ERROR);
}
}
}
/* make the application a daemon */
void daemonize(void)
{
int pid;
int i;
if (pid = fork())
exit(RUN_OK); /* parent exits */
else if (pid < 0)
exit(FATAL_ERROR); /* fork() failed */
/* first child process */
setsid();
if (pid = fork())
exit(RUN_OK); /* first child exits */
else if(pid < 0)
exit(FATAL_ERROR); /* fork() failed */
/* second child */
for (i = 0; i < NOFILE; ++i) /* close all files */
close(i);
chdir("/"); /* change directory to root(/) directory */
umask(0); /* set proper file mask */
}
/* read configuration */
int read_config(void)
{
return RUN_OK; /* OK */
}
/* initialize application */
int app_init(void)
{
return RUN_OK; /* OK */
}
利用Sun公司最新推出的C/C++/Fortran开发及编译环境Sun Studio 11,使用以下命令将myapp.c编译成可执行程序myapp。
| $ /opt/SUNWspro/bin/cc -o ./myapp ./myapp.c |
或者直接使用Solaris 10自带的gcc编译器将myapp.c编译成可执行程序myapp。
| $ /usr/sfw/bin/gcc -o ./myapp ./myapp.c |
编译成功后在当前目录下会生成myapp可执行程序。本例假设当前目录为/export/home/smfdemo。直接在命令行输入. /myapp就可以启动myapp为后台守护进程,同时可以在/tmp目录下找到myapp.log文件。使用“/usr/bin/tail -f /tmp/myapp.log”命令可以看到进程myapp不断在日志文件中报告自己的存在。为了使这个进程在服务器启动时自动运行,传统做法一般需要写三个shell脚本。其中一个shell脚本置于/etc/init.d目录下用以实际启动和停止myapp服务(例如<表2所示的 /etc/init.d/myapp.sh)。另外两个shell脚本的名字分别以S和K开头(例如,S79myapp和K79myapp),置于合适的 /etc/rc?.d目录下(例如,/etc/rc2.d目录下),分别以不同参数(start和stop)调用 /etc/init.d/myapp.sh。操作系统在boot时会自动运行S开头的脚本以启动myapp服务,而在shutdown时自动运行K开头的脚本以关闭myapp服务。
| 论坛热门帖子: | [lch203] 写得蛮好的linux学习笔记(10-21) [黑马制造] 学习java的30个目标(10-19) [笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19) [udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18) [沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18) |
| TAG标签: | 服务 部署 应用 SMF 可以 myapp 启动 文件 exit 方法 |
注册
个人空间
