Chinaunix首页 | 论坛 | 博客
  • 博客访问: 345941
  • 博文数量: 59
  • 博客积分: 2000
  • 博客等级: 大尉
  • 技术积分: 646
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-14 12:09
文章分类

全部博文(59)

文章存档

2009年(2)

2008年(57)

我的朋友

分类: C/C++

2008-07-21 09:58:42

本程序是一个使用FIFO进行进程间通信的典型程序lucy.c创建了FIFO write──fifo用于向程序peter.c发送信息:程序创建了FIFO read-fifo,用于向lucy.c发送消息。编译本程序,先运行peter.c再运行lucy.c就可以了。
源程序如下:
//filename:lucy.c
#include
#include
#include
#include
#include
#include
#include
#include

int main(viod)
{
    char write_fifo_name[]="write-fifo";
    char read_fifo_name[]="read-fifo";
    int write_fd,read_fd;
    char buf[256];
    int len;
    struct stat_buf;
   
    int ret=mkfifo(write_fifo_name,S_IRUSR | S_IWUSR);
    if(ret==-1)
    {printf("failed to create FIFO %s:%s\n",write_fifo_name,strerror(errno));
    exit(-1);
        }
       
    write_fd=open(write_fifo_name,O_WRONLY);
        if(write_fd==-1)
        {printf("failed to open FIFO %s:%s\n",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("perter:%s\n",buf);
            }
}
}






//filename:peter.c
#include
#include
#include
#include
#include
#include
#include
#include

int main(viod)
{
    char write_fifo_name[]="read-fifo";
    char read_fifo_name[]="write-fifo";
    int write_fd,read_fd;
    char buf[256];
    int len;
    //struct stat_buf;
   
    int ret=mkfifo(write_fifo_name,S_IRUSR | S_IWUSR);
    if(ret==-1)
    {
        printf("failed to create FIFO %s:%s\n",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("failed to open FIFO %s:%s\n",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));
    }
}



阅读(3108) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~