Linux系统编程_进程间通信

IPC通信方式:管道(无名管道和命名管道)、消息队列、信号量、共享存储、socket、streams等(同PC内进程通信);socket和streams支持不同PC间进程通信


一、管道:

半双工、父子间、只存在于内存


1.无名管道


int pipe(int fd[2])  //成功返回0   fd[0]  读打开  fd[1]  写打开
注意:wait()放在代码末
阻塞:当代码条件不满足时,无法往下执行

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	int fd[2];

	int pid;

	char buf[128];

//	int pipe(int pipefd[2]);

	if(pipe(fd) == -1){
		printf("creat pipe failed\n");
	}
	pid = fork();
	
	if(pid<0){
		printf("creat child failed\n");
	}
	else if(pid > 0){
		sleep(3);
		printf("this is father\n");

		close(fd[0]);
		write(fd[1],"hello from father",strlen("hello form father"));
		wait();
	}else{
		printf("this is child\n");
		close(fd[1]);
		read(fd[0],buf,128);
		printf("read from father: %s\n",buf);
		exit(0);
	}
	

	return 0;
}

2.命名管道:存在于磁盘

1 #include <sys/stat.h>
2 // 返回值:成功返回0,出错返回-1
3 int mkfifo(const char *pathname, mode_t mode);

FIFO,也称为命名管道,它是一种文件类型。
1.FIFO可以在无关的进程之间交换数据,与无名管道不同。
2.FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。

open() creat 文件权限  r:4  w:1   x:2

其中的 mode 参数与open函数中的 mode 相同。一旦创建了一个 FIFO,就可以用一般的文件I/O函数操作它。

当 open 一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别:

  • 若没有指定O_NONBLOCK(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO。类似的,只写 open 要阻塞到某个其他进程为读而打开它。

  • 若指定了O_NONBLOCK,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO。

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

//       int mkfifo(const char *pathname, mode_t mode);
int main()
{
	if( (mkfifo("./file",0600) == -1) && errno!=EEXIST){
		printf("mkfifo failuer\n");
		perror("why");
	}

	int fd = open("./file",O_RDONLY);
	printf("open success\n");


	return 0;
}



二、消息队列(存在于内核中)

有AB两个进程
系统上内核上有多个队列;所以尽管两个通信的进程结束了,消息也依然存在内核中
1.B如何加消息到队列,(将结构体加入到来链表中)
2.A如何读取队列的消息。AB使用同一队列才可通信
3.如何创建消息队列

  • // 创建或打开消息队列:成功返回队列ID,失败返回-1
  • <
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值