Linux进程间的通信——有名管道fifo与守护进程deamon
2016-10-18 09:47
591 查看
前面已经有两篇文章分别对有名管道fifo和守护进程deamon有过介绍。
这里主要是以一个简单的实例来介绍如何结合使用fifo与deamon。
eg:通过fifo有名管道实现一个窗口收取信息,另一个窗口发送信息,其中收取信息窗口将收取信息进程设置为守护进程。
结果:
写窗口
读窗口
读取进程为守护进程,过程中可以做其他内容,一旦有消息发送过来,就会显示在屏幕
这里主要是以一个简单的实例来介绍如何结合使用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; }
结果:
写窗口
读窗口
读取进程为守护进程,过程中可以做其他内容,一旦有消息发送过来,就会显示在屏幕
相关文章推荐
- linux下进程间的通信——有名管道fifo学习笔记
- Linux进程通信 有名管道实现守护进程
- linux进程通信----FIFO(有名管道)
- linux进程通信--有名管道(FIFO)(含实例代码)
- Linux进程通信:命名管道FIFO小结
- linux进程通信-有名管道
- Linux 进程通信(有名管道)
- linux 练习七 线程键用有名管道FIFO通信
- linux进程通信机制之无名管道&有名管道
- (FIFO)有名管道在无亲缘进程间的通信
- 命名管道(FIFO) Linux进程进程间的通信之命名管道(FIFO)
- 【Linux进程通信】管道,FIFO
- Linux进程通信:命名管道FIFO小结
- linux进程通信--有名管道
- linux 命名管道fifo实现进程间小数据通信
- Linux下的有名管道(06)---使用两个管道实现两个进程之间的通信(手机模式)
- Linux下进程的通信方式: 有名管道(命名管道)
- linux 进程编程:有名管道fifo
- Linux进程通信:命名管道FIFO小结
- linux进程间管道通信pipe与fifo