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

#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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值