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

Linux进程间的通信——有名管道fifo与守护进程deamon

2016-10-18 09:47 591 查看
前面已经有两篇文章分别对有名管道fifo和守护进程deamon有过介绍。

这里主要是以一个简单的实例来介绍如何结合使用fifo与deamon。

eg:通过fifo有名管道实现一个窗口收取信息,另一个窗口发送信息,其中收取信息窗口将收取信息进程设置为守护进程。

/*
============================================================================
Name        :
readfifo.c
Author      : Allen
Version     :
Copyright   : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void setdaemon()
{
pid_t pid = fork();
if (pid ==-1)
{
printf("fork failed: %s\n", strerror(errno));
exit(0);
}
if (pid == 0)
{
setsid();
chdir("/");
umask(0);
/*close(STDOUT_FILENO);//这里要注释掉,否则屏幕不能输入信息
close(STDIN_FILENO);
close(STDERR_FILENO);
*/

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

int readfifo()
{
int fd = open("/home/vicent/6/fifo1", O_RDONLY);
if (fd == -1)
{
printf("open failed %s\n", strerror(errno));
return -1;
}
char buf[1024];
memset(buf, 0, sizeof(buf));
int len = 0;
while ((len = read(fd, buf, sizeof(buf)))>0)
{
write(STDOUT_FILENO,buf,sizeof(buf));
//printf("%s",buf);
memset(buf, 0, sizeof(buf));
}
close(fd);
return 0;
}

int main()
{
setdaemon();
readfifo();
return 0;
}


/*
* writefifo.c
*
*  Created on: 2016年10月16日
*      Author: Allen
*/

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int writefifo()
{
int fd = open("/home/vicent/6/fifo1", O_WRONLY);
if (fd == -1)
{
printf("open failed %s\n", strerror(errno));
return -1;
}
char buf[1024];
memset(buf, 0, sizeof(buf));

while (1)
{
memset(buf, 0, sizeof(buf));
read(STDIN_FILENO, buf, sizeof(buf));
write(fd, buf, sizeof(buf));
}

close(fd);
return 0;
}

int main()
{
writefifo();
return 0;
}


结果:

写窗口



读窗口

读取进程为守护进程,过程中可以做其他内容,一旦有消息发送过来,就会显示在屏幕

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息