应用部署为Solaris 10 SMF服务( 二 )


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服务 。
表2.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/sbin/sh
###############################################################################
# /etc/init.d/myapp.sh #
###############################################################################
RUN_OK=0
CONFIG_ERROR=1
FATAL_ERROR=2
case "$1" in
'start')
/export/home/smfdemo/myapp
if [ $? -eq $CONFIG_ERROR ]; then
exit $CONFIG_ERROR
fi
if [ $? -eq $FATAL_ERROR ]; then
exit $FATAL_ERROR
fi

推荐阅读