主题 : 有名管道通信 复制链接 | 浏览器收藏 | 打印
级别: 新手上路
UID: 18505
精华: 0
发帖: 48
金钱: 250 两
威望: 50 点
综合积分: 96 分
注册时间: 2010-04-10
最后登录: 2011-05-05
楼主  发表于: 2010-06-11 10:13

 有名管道通信

有名管道用在任意进程之间的通信
读进程
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO "/tmp/myfifo"

main(int argc,char** argv)
{
    char buf_r[100];
    int  fd;
    int  nread;
    
    /* 创建管道 */
    if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
        printf("cannot create fifoserver\n");
    
    printf("Preparing for reading bytes...\n");
    
    memset(buf_r,0,sizeof(buf_r));
    
    /* 打开管道 */
    fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
    if(fd==-1)
    {
        perror("open");
        exit(1);    
    }
    while(1)
    {
        memset(buf_r,0,sizeof(buf_r));
        
        if((nread=read(fd,buf_r,100))==-1)
        {
            if(errno==EAGAIN)
                printf("no data yet\n");
        }
        printf("read %s from FIFO\n",buf_r);
        sleep(1);
    }    
    pause(); /*暂停,等待信号*/
    unlink(FIFO); //删除文件
}

写进程
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO_SERVER "/tmp/myfifo"

main(int argc,char** argv)
{
    int fd;
    char w_buf[100];
    int nwrite;
        
    /*打开管道*/
    fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);
    
    if(argc==1)
    {
        printf("Please send something\n");
        exit(-1);
    }
    
    strcpy(w_buf,argv[1]);
    
    /* 向管道写入数据 */
    if((nwrite=write(fd,w_buf,100))==-1)
    {
        if(errno==EAGAIN)
            printf("The FIFO has not been read yet.Please try later\n");
    }
    else
        printf("write %s to the FIFO\n",w_buf);
}

main(int argc,char** argv) 表示在运行该程序是后面可以跟参数 例如写进程的文件名为fifo_write则 ./fifo_write hello ,表示hello传给argv
然后再运行读进程,但是这样并没有成功,因为管道是在读进程中创建的,所以必须先运行读进程。
注意,管道中的数据读出来后就没有了
学习交流
*無鈳取玳
级别: 论坛版主
UID: 27
精华: 12
发帖: 5398
金钱: 40120 两
威望: 17929 点
综合积分: 11036 分
注册时间: 2008-01-16
最后登录: 2014-11-22
1楼  发表于: 2010-06-11 11:05
谢谢分享
"If you have an apple and I have an apple and we exchange apples, then you and I will
still each have one apple. But if you have an idea and I have an idea and we exchange
these ideas, then each of us will have two ideas."