一、无名通道
局限性:只能父子进程之间进行通信
int pipe(int pipefd[2])
利用无名通道进行读写数据:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
pid_t pid;
int fd[2];
if (pipe(fd) < 0)
{
perror("pipe fork error!");
exit(1);
}
pid = fork();
if (pid == -1)
{
perror("fork error!");
exit(1);
}
if (pid == 0)
{
close(fd[0]);
char buf[100];
while (1)
{
scanf("%s",buf);
write(fd[1], buf, strlen(buf));
}
}
else if (pid > 0)
{
char buf[100] = {0};
while (1)
{
int len = read(fd[0], buf, sizeof(buf));
buf[len] = '\0';
printf("recv = %s\n", buf);
}
}
return 0;
}
二、有名通道
任何两个不相干的进程都可以进行通信
//read.c 子进程进行读数据
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
if (mkfifo("/tmp/p1", 0644) < 0)
{
perror(“mkfifo error”);
exit(1);
}
int fd = open("/tmp/p1", O_RDONLY);
if (fd == -1)
{
perror(“open file error!”);
exit(1);
}
char buf[100] = {0};
while (1)
{
int len=read(fd,buf,sizeof(buf));
buf[len]='\0';
printf("recv=%s\n",buf);
}
return 0;
}
//write.c 父进程进行写数据
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = open("/tmp/p1", O_WRONLY);
if (fd == -1)
{
perror(“open file error!”);
exit(1);
}
char buf[100] = {0};
while (1)
{
scanf("%s", buf);
write(fd, buf, strlen(buf));
}
return 0;
}
三、消息队列
(1)传送有格式的消息流:通过不同的id来控制传输的数据
(2)多进程网状交叉通信时,消息队列是上上之选
(3)能实现大规模数据的通信
API:
int msgget(key_t key,int msgflg(0644));创建消息队列
int msgsnd (int msqid,const void *msgp,size_t msgsz,int msgflg);传输消息队列
int msgctl 结束队列