[技術] Linux具名管線(FIFOs)編程

Written on 8:39 下午 by Yu Lai

From: http://blog.csdn.net/lcrystal623/archive/2007/03/16/1531201.aspx

具名管線可以用於任何兩個程序間通信,因為有名字可引用。注意管道都是單向的,因此雙方通信需要兩個管道。

下面分別是這兩個程式代碼,同樣是Lucy先運行,然後是Peter。

fifoLucy.c

#include <sys/types.h>
#include <sys/stat.h>

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
char write_fifo_name[] = "lucy";
char read_fifo_name[] = "peter";
int write_fd, read_fd;
char buf[256];
int len;
struct stat stat_buf;

int ret = mkfifo(write_fifo_name, S_IRUSR | S_IWUSR);
if( ret == -1)
{
printf("Fail to create FIFO %s: %s",write_fifo_name,strerror(errno));
exit(-1);
}

write_fd = open(write_fifo_name, O_WRONLY);
if(write_fd == -1)
{
printf("Fail to open FIFO %s: %s",write_fifo_name,strerror(errno));
exit(-1);
}

while((read_fd = open(read_fifo_name,O_RDONLY)) == -1)
{
sleep(1);
}

while(1)
{
printf("Lucy: ");
fgets(buf, 256, stdin);
buf[strlen(buf)-1] = '\0';
if(strncmp(buf,"quit", 4) == 0)
{
close(write_fd);
unlink(write_fifo_name);
close(read_fd);
exit(0);
}
write(write_fd, buf, strlen(buf));
len = read(read_fd, buf, 256);
if( len > 0)
{
buf[len] = '\0';
printf("Peter: %s\n", buf);
}
}
}
fifoPeter.c
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>

int main(void)
{
char write_fifo_name[] = "peter";
char read_fifo_name[] = "lucy";
int write_fd, read_fd;
char buf[256];
int len;

int ret = mkfifo(write_fifo_name, S_IRUSR | S_IWUSR);
if( ret == -1)
{
printf("Fail to create FIFO %s: %s",write_fifo_name,strerror(errno));
exit(-1);
}

while((read_fd = open(read_fifo_name, O_RDONLY)) == -1)
{
sleep(1);
}

write_fd = open(write_fifo_name, O_WRONLY);
if(write_fd == -1)
{
printf("Fail to open FIFO %s: %s", write_fifo_name, strerror(errno));
exit(-1);
}

while(1)
{
len = read(read_fd, buf, 256);
if(len > 0)
{
buf[len] = '\0';
printf("Lucy: %s\n",buf);
}
printf("Peter: ");
fgets(buf, 256, stdin);
buf[strlen(buf)-1] = '\0';
if(strncmp(buf,"quit", 4) == 0)
{
close(write_fd);
unlink(write_fifo_name);
close(read_fd);
exit(0);
}
write(write_fd, buf, strlen(buf));
}
}

If you enjoyed this post Subscribe to our feed

No Comment

張貼留言