|
|
程序代码如下:
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <mysql.h>
#include <mysql_version.h>
#include <errmsg.h>
//#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
void init_daemon(void)
{
int pid;
int i;
if(pid=fork())
exit(0);//father process,and kill it.
else if(pid < 0)
exit(1);//fail fork(),exit
setsid();
if(pid=fork())
exit(0);
else if(pid < 0)
exit(1);
for(i=0; i < NOFILE; i++)
close(i);
//chdir("/tmp");//change dir to /tmp
umask(0);
signal(SIGCHLD,SIG_IGN);
return;
}
int main(int argc,char* argv[])
{
MYSQL mysql;
MYSQL_RES *result;
MYSQL_ROW row;
char channel[30];
unsigned int num_fields;
unsigned int i;
int fd;
char content[1024];
char tmp[]="callXXXXXX";
char command[100];
char command1[100];
time_t tt;
struct tm *p;
char time1[100];
char time2[100];
init_daemon();
time(&tt);
p = localtime(&tt);
snprintf(time1,100,"%d-%d-%d %d:%d:%d",(1900+p->tm_year),(1+p->tm_mon),p->tm_mday,p->tm_hour,(p->tm_min+1),p->tm_sec);
snprintf(time2,100,"%d-%d-%d %d:%d:%d",(1900+p->tm_year),(1+p->tm_mon),p->tm_mday,p->tm_hour,(p->tm_min-1),p->tm_sec);
memset(content,0,1024);
memset(channel,9,30);
printf("begin %s to %s",time2,time1);
if(!mysql_init(&mysql)){
return 0;
}
if(arg == 1)
strcpy(channel,"ZAP/g3");
else
strcpy(channel,argv[1]);
printf("%s",argv[0]);
//if(mysql_real_connect(&mysql,"192.168.166.166","jim","jimu9n2","astbill",0,NULL,0))
if(mysql_real_connect(&mysql,"192.168.88.246","dblink","5LMY$68","voip",0,NULL,0))
{
snprintf(command1,100,"select * from webcall where state = 0 and calltime > '%s' and calltime < '%s'",time2,time1);
printf("%s",command1);
//mysql_query(&mysql,command1);
mysql_query(&mysql,"select *from webcall where state = 0");
result = mysql_store_result(&mysql);
if(result == NULL)
return 1;
num_fields = mysql_num_fields(result);
sleep(10);//sleep 10 sec
while((row = mysql_fetch_row(result)))
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for(i = 0; i < num_fields; i++)
{
printf("[%.*s]",(int) lengths,row ? row : "NULL");
}
printf("\n");
fd=mkstemp(tmp);
if(fd < 0)
{
printf("Can't open file");
return;
}
if(argc == 1)
snprintf(channel,30,"ZAP/g3/%s",row[2]);
else
snprintf(channel,30,"%s/%s",argv[1],row[2]);
snprintf(content,1024,"Channel: %s\nCallerid: %s\nAccount: %s:%s\nMaxRetries: 3\nRetryTime: 60\nWaitTime: 120\nContext: webcall\nExtension: %s\nPrioriry: 1\n\0",channel,row[3],row[1],row[2],row[3]);
printf("%s",content);
write(fd,content,strlen(content));
snprintf(command,100,"mv call* /var/spool/asterisk/outgoing/call%s.call\0",row[1]);
printf("shell command is%s\n",command);
system(command);
tt=time(0);//set time to 0
snprintf(command,100,"update webcall set state = 1 where calltime = '%s'\0",row[4],asctime(localtime(&tt)));
printf("%s\n",command);
mysql_query(&mysql,command);
close(fd);
}
}
mysql_close(&mysql);
clode(fd);
printf("test");
return 1;
}
很急的 ,请大家帮忙!然后问下要写一个守护进程要注意什么地方??谢谢! |
|