进程间通信
来源:互联网 发布:知商金融活动 编辑:程序博客网 时间:2024/06/17 02:42
在进程间的通信手段大概分为以下几种:
1. 管道(Pipe)和有名管道(FIFO)
2. 信号(Signal)
3. 消息队列
4. 共享内存
5. 信号量
6. 套接字
今天我主要学习了管道,信号和共享内存三种方法,我主要复习管道的用法。
管道分为pipe 和 fifo 两种:
pipe 的创建:int pipe(int fd[2])。
管道两端分别用fd[0]和fd[1]描述,管道两端的任务固定,fd[0]只能用于读,称为管道读端;fd[1]只能用于写,称为管道写端。如果某进程要读取管道中的数据,那么该进程应当关闭fd[1],同时向管道写数据的进程应当关闭fd[0]。向管道中写数据类似。
例程:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
int main()
{
int fd[2] = {0};
int ret = pipe(fd);
if (-1 == ret)
{
perror("pipe");
exit(1);
}
pid_t pid = fork();
if (-1 == pid)
{
perror("fork");
exit(2);
}
char buffer[32] = {0};
if (0 == pid)
{
while(1)
{
if (-1 == read(fd[0], buffer, 32))
{
perror("read");
exit(3);
}
printf("c recv: %s\n", buffer);
if (strcmp(buffer, "exit") == 0)
{
exit(0);
}
if (-1 == write(fd[1], buffer, 32))
{
perror("write");
exit(4);
}
sleep(1);
memset(buffer, 0, 32);
}
}
else
{
while(1)
{
printf("p scanf : ");
scanf("%s", buffer);
if (-1 == write(fd[1], buffer, 32))
{
perror("write");
exit(4);
}
if (strcmp(buffer, "exit") == 0)
{
exit(0);
}
sleep(1);
if (-1 == read(fd[0], buffer, 32))
{
perror("read");
exit(3);
}
printf("p recv : %s\n", buffer);
}
exit(0);
}
}
fifo 的创建:
mkfifo("/root/Desktop/fifo/myfifo", S_IRWXU);(前面是标明创建的路径,后面是标明创建文件的权限)
完整创建fifo:
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
int main()
{
int fd = mkfifo("/root/Desktop/fifo/myfifo", S_IRWXU);
if (-1 == fd)
{
perror("mkfifo");
exit(1);
}
}
fifo创建后,存在与硬盘上,必须先用open()将其打开。打开fifo的进程可能会被阻塞,如果同时以读写方式打开,则一定不会阻塞。如果以只读方式打开,则调用open的进程将会被阻塞直到有写方打开管道。
例程:
/*write*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd = open("./myfifo", O_WRONLY);
if (-1 == fd)
{
perror("open");
exit(1);
}
char buf[32] = "hello";
if (-1 == write(fd, buf, 5))
{
perror("write");
exit(2);
}
close(fd);
return 0;
}
/*read*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd = open("./myfifo", O_RDONLY);
if (-1 == fd)
{
perror("open");
exit(1);
}
char buf[32] = {0};
if (-1 == read(fd, buf, 5))
{
perror("read");
exit(2);
}
printf("%s\n", buf);
close(fd);
return 0;
}
- 进程&进程间通信
- 信号通信(进程间通信)
- 进程间通信-管道通信
- 进程间通信--管道通信
- [进程通信] 进程间通信 之 管道
- 进程与进程间通信
- 【IO进程】进程间通信
- 进程间通信
- 进程间通信方式
- 进程间通信IPC
- 进程间通信
- 操作系统:进程间通信
- 进程间的通信
- 进程间通信
- 进程间通信IPC
- 进程间通信
- 进程间通信总结
- 进程间管道通信
- Windows下Nginx配置SSL实现Https访问(包含证书生成) Windows下Nginx配置SSL实现Https访问(包含证书生成) 首先要说明为什么要实现https? HTTP
- 非循环双链表应用
- java中的集合
- Myeclipse下的 项目改为 eclipse
- mysql:using password : yes
- 进程间通信
- [树的点分治] [树形DP] [BZOJ2599] [IOI2011] Race
- python通过ctypes调用dll
- s2sh集成dataSource配置无效的问题 -Access denied for user 'sa'@'localhost'
- ubuntu安装那些事
- 快速创建c文件脚本
- CGI FastCGI PHP-CGI PHP-FPM 区分
- select() +socket 实现 socket服务器 -Linux
- java集合总结