管道及消息队列

一、无名通道
局限性:只能父子进程之间进行通信
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 结束队列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值