命名管道

无名管道:

#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 80

int main(void)
{
int n;
int fd[2];
pid_t pid;
char line[MAXLINE];

if (pipe(fd) < 0) {
perror("pipe");
exit(1);
}
if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}
if (pid > 0) { /* parent */
close(fd[0]);
write(fd[1], "hello world\n", 12);
wait(NULL);
} else { /* child */
close(fd[1]);
n = read(fd[0], line, MAXLINE);
write(STDOUT_FILENO, line, n);
}

无名管道只能在单个进程间通信。

命名管道:

有三个进程:

mkfifo进程:

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
int main(void)
{
char buf[80];
int fd;
unlink( "zieckey_fifo" );
mkfifo( "zieckey_fifo", 0777 );
}


写进程:

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
int main(void){
int fd;
char s[] = "Hello!\n";
fd = open( "zieckey_fifo", O_WRONLY );
while(1) {
write( fd, s, sizeof(s) );
sleep(1);
}
return 0;
}


读进程:

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
int main(void){
int fd;
char buf[80];
fd = open( "zieckey_fifo", O_RDONLY );
while(1) {
read( fd, buf, sizeof(buf) );
printf("%s\n", buf);
sleep(1);
}
return 0;
}


三个同时进行,可见多进程之间可以传输了。

其实感觉mkfifo进程没啥作用,它可以先结束的,因为它只建了个文件而已。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值