有名管道-非父子进程间通信

有名,即文件系统中存在对应文件节点,每个文件节点都有一个inode号。

open: 普通文件
mkfifo: 创建管道
socket:创建套接字
mknod:字符设备文件
mkdir: 目录文件

mkfifo函数: 创建管道文件
函数形式:int mkfifo(const char * filename, mode_t mode);
参数:管道文件名;权限,文件权限仍然和umask有关
返回:成功返回0,失败返回-1

创建有名管道mkfifo,打开open,读read,写write,关闭close。

非父子进程间通信
第一个进程:

#include "unistd.h"
#include "stdio.h"
#include "sys/types.h"
#include "stdlib.h"
#include "fcntl.h"
int main()
{
 int fd;
 int i;
 char process_inter=0;
 fd=open("./myfifo",O_WRONLY);
 if(fd <0)
 {
   printf("open myfifo failure\n");
   return -1;
 }
 printf("open myfifo sucess\n");
 
 for(i=0;i<5;i++)
 {
   printf("this is first process i=%d\n",i);
   usleep(100);
 }
 process_inter=1;
 sleep(5);
 write(fd,&process_inter,1);
 while(1);
 return 0;  
}

运行结果

open myfifo sucess
this is first process i=0
this is first process i=1
this is first process i=2
this is first process i=3
this is first process i=4

第二个进程:

#include "unistd.h"
#include "stdio.h"
#include "sys/types.h"
#include "stdlib.h"
#include "fcntl.h"
int main()
{
 int fd;
 int i;
 int process_inter=0;
 fd=open("./myfifo",O_RDONLY);
 if(fd <0)
 {
   printf("open myfifo failure\n");
   return -1;
 }
 printf("open myfifo sucess\n");
 
 read(fd,&process_inter,1);
 while(process_inter == 0);
 
 for(i=0;i<5;i++)
 {
   printf("this is second process i=%d\n",i);
   usleep(100);
 }
 while(1);
 return 0;  
}

运行结果

open myfifo sucess
this is second process i=0
this is second process i=1
this is second process i=2
this is second process i=3
this is second process i=4
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值