创建或者连接管道+++检查管道空间是否够写入本消息++++删除管道

/**
函数名:nFIFOOpen
功能 :创建或者连接管道
参数 :
nFIFOKey 关键字
返回值:
-1 失败
>0的数 管道描述符号
注意: 管道实现忽略size参数
**/

int nFIFOOpen(int nFIFOKey)
{
    if(nFIFOKey <= 0)
    {
        return -1;
    }

    int  fd;
    int  iRc;
    struct stat st;
    char sFifoName[128];

    /****MSGIN FIFO ****/
    memset(&st,'',sizeof(st));
    memset(sFifoName,0x00,sizeof(sFifoName));
    sprintf(sFifoName,"%s/tmp/x%x.fifo",getenv("SWWORK"),nFIFOKey);
    fd=open(sFifoName,O_RDWR|O_NONBLOCK);    /**非阻塞方式**/
    if (fd < 0)
    {
        iRc=mkfifo(sFifoName,0644);
        if(iRc)
        {
            printf("创建FIFO[x%x.fifo]失败[%d]
",nFIFOKey,errno);
            return(-1);
        }
        fd=open(sFifoName,O_RDWR);
        if(fd<0)
        {
            printf("连接FIFO[x%x.fifo]失败[%d]
",nFIFOKey,errno);
            return(-1);
        }
    }

    fstat(fd,&st);
    if(!S_ISFIFO(st.st_mode))
    {
        printf("指定文件[x%x.fifo]不是FIFO[%d]
",nFIFOKey,errno);
        return(-1);
    }

    return(fd);
}

/**
函数名:nFIFOCheckSize
功能 :检查管道空间是否够写入本消息
参数 :
nFIFOId 管道描述符
nLength 写入长度
返回值:
0 空间足够
-1 空间不够
**/

int nFIFOPut(int nFIFOId,int iKey)
{
    if(nFIFOId <= 0 || iKey <= 0)
    {    
        return -1; 
    } 

    int iRc; 
    int iLen;
    char sKey[20];
    char sTmp[50];

    memset(sKey,0x00,sizeof(sKey));
    memset(sTmp,0x00,sizeof(sTmp));

    sprintf(sKey,"%d",iKey);
    iLen = strlen(sKey);
    sprintf(sTmp,"%010d%s",iLen,sKey);

    iRc = write(nFIFOId, sTmp, strlen(sTmp));
    if(iRc<=0)
    {
        return -1;
    }

    return(0);
}

int nFIFOGet(int nFIFOId,int *iKey)
{
    if(nFIFOId <= 0 || iKey == NULL)
    {
        return -1;
    }

    int iRc;
    int iLen;
    char pcBuf[50];
    
    /*先从管道中读取需要接受的数据的长度*/    
    memset(pcBuf, 0x00, sizeof(pcBuf));    
    iRc=read(nFIFOId, pcBuf, 10);
    if(iRc<=0){
        return(-1);
    }
    
    /*读取保存数据的队列的key值*/
    iLen = atoi(pcBuf);
    memset(pcBuf,0x00,sizeof(pcBuf));
    iRc=read(nFIFOId, pcBuf, iLen);
    if(iRc<=0){
        return(-1);
    }
    
    *iKey = atoi(pcBuf);

    return 0;
}

/**
函数名:nFIFORemove
功能 :删除管道
参数 :
nFIFOId 管道描述符
返回值:
0 成功
-1 失败
**/

int nFIFORemove(int nFIFOId){
    if(nFIFOId <= 0)
    {
        return -1;
    }
    close(nFIFOId);
}
原文地址:https://www.cnblogs.com/sherlockhomles/p/3214088.html