命名管道

#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 );
if ( fork() > 0 )
{
char s[] = "Hello!\n";
fd = open( "zieckey_fifo", O_WRONLY );
write( fd, s, sizeof(s) );
//close( fd );
}
else
{
fd = open( "zieckey_fifo", O_RDONLY );
read( fd, buf, sizeof(buf) );
printf("The message from the pipe is:%s\n", buf );
//close( fd );
}
return 0;

}



1. 创建命名管道
#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 );
}

2. 写命名管道代码

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.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;
}

3. 读命名管道代码

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.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;

}



下面通过例子来说明该命令的用法:
创建一fifo
[root@localhost ~]# mkfifo -m 777  myfifo
将cat命令的输出作为此myfifo的输入,并放在后台运行
[root@localhost ~]# cat /etc/passwd > myfifo &
[10] 6285
再用cut命令从该myfifo中读出数据进行处理
[root@localhost ~]# cut -d: -f1-3 < myfifo 

你可能感兴趣的:(命名管道)