23,115
社区成员
发帖
与我相关
我的任务
分享
/* ************************************************************************
* Filename: t.c
* Description:
* Version: 1.0
* Created: 2017年07月29日 12时28分27秒
* Revision: none
* Compiler: gcc
* Author: fyh
* Company: henu
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
//我想在守护进程的主程序中在文件中每隔3S中写入一段字符
void catch(int signo)
{
int fd = open("1", O_RDWR|O_CREAT, 0644);
write(fd, "---\n", 4);
}
void my() //定义守护进程
{
pid_t pid, sid;
pid = fork();
if (pid > 0)
return ;
sid = setsid();
int ret = chdir("/home");
umask(0002);
close(0);
int fd = open("/dev/null", O_RDWR);
dup2(0, 1);
dup2(0, 2);
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGALRM);
struct sigaction temp1, temp2;
temp1.sa_handler = catch;
temp1.sa_flags = 0;
temp1.sa_mask = set;
sigaction(SIGALRM, &temp1, NULL); //注册
while (1)
{
alarm(3); //每个3S发送一个信号
//sleep(3);
}
}
int main(int argc, char argv[])
{
my();
while (1);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <pthread.h>
//real jobs
void timer_notify_cb(union sigval val)
{
int fd = open("1", O_RDWR|O_CREAT|O_APPEND, 0644);
write(fd, "---\n", 4);
close(fd);
}
void cycling_job_timer(int period)
{
/* Variable Definition */
timer_t id;
struct timespec spec;
struct sigevent ent;
struct itimerspec value;
struct itimerspec get_val;
/* Init */
memset(&ent, 0x00, sizeof(struct sigevent));
memset(&get_val, 0x00, sizeof(struct itimerspec));
/* create a timer */
ent.sigev_notify = SIGEV_THREAD;
ent.sigev_notify_function = timer_notify_cb;
timer_create(CLOCK_MONOTONIC, &ent, &id);
/* start a timer */
value.it_value.tv_sec = period;
value.it_value.tv_nsec = 0;
value.it_interval.tv_sec = period;
value.it_interval.tv_nsec = 0;
timer_settime(id, 0, &value, NULL);
}
void daemonize(void)
{
pid_t pid;
int nullfd;
/* step1 : clear file creation mask */
umask(0);
/* step2 : fork */
pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
else if (pid != 0) { // parent process exit
printf("== the deamon pid is %u\n", pid);
exit(EXIT_SUCCESS);
}
/* step3 : setsid */
setsid();
/* setp4 : chdir */
chdir("/tmp/");
/* step5 : close all open file descriptions */
/* step6 : redirect standard IO/error */
nullfd = open("/dev/null", O_RDWR);
dup2(nullfd, STDIN_FILENO);
dup2(nullfd, STDOUT_FILENO);
dup2(nullfd, STDERR_FILENO);
/* regeister timer */
cycling_job_timer(3);
}
int main(int argc, char argv[])
{
daemonize();
while (1) {
sleep(1);
}
return 0;
}