您的位置:首页 > 运维架构 > Linux

Linux守护进程加上发送信号固定模式

2016-07-10 10:28 483 查看
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <ctype.h>
#include <errno.h>
int singnal1(int signo, void (*func)(int))
{
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
return sigaction(signo, &act, &oact);
}

void setdaemon()
{
pid_t pid, sid;
pid = fork();
if (pid < 0)
{
exit(EXIT_FAILURE);
}

if (pid > 0)
{
exit(EXIT_SUCCESS);
}

if ((sid = setsid()) < 0)
{
printf("setsid failed %s\n", strerror(errno));
exit(EXIT_FAILURE);
/*chdir("/");
umask(0);
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);*/
}

}

void listenfifo()
{
const char *sfifoname = "fifo1";
int len = 0;
char buf[128];
memset(buf, 0, sizeof(buf));
int fd = open(sfifoname, O_RDONLY);//打开fifo管道文件
if (fd == -1)
{
printf("open %s failed, %s\n", sfifoname, strerror(errno));
}
len = read(fd, buf, sizeof(buf)); // 进程阻塞,直到数据来了才返回
if (len > 0)
{
if (buf[strlen(buf) - 1] == '\n')
{
buf[strlen(buf) - 1] = 0;
}
close(STDOUT_FILENO);
open(buf, O_WRONLY);
}
close(fd);
}

void catch_Signal(int Sign)
{
switch (Sign)
{
case SIGINT:
listenfifo();
break;
}
}

int main(void)
{
setdaemon();//吧进程设置为daemon状态
singnal1(SIGINT, catch_Signal);//捕捉int信号
while (1)
{
puts("!!!Hello World!!!");
sleep(1);
}
return EXIT_SUCCESS;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: