繁体   English   中英

我如何 PIPE 文件输入或 output 缓冲区刷新?

[英]How can i PIPE file input or output buffer flush?

今天我的代码输入有问题 & output 缓冲区刷新问题。

这个问题是

第一个 Process(#1) 的代码....

int sign_sender(char* command)
{
    int f , len;

    f=open(PIPE_NAME,O_RDWR);

    if(f<0)
    {
        printf("open fail : %s\n",strerror(errno));
        exit(1);
    }

    while(1)
    {
        len=strlen(command);
        if(len<=0)
        {
            continue;
        }
        write(f,command,len);
        printf("write...\n");
        sleep(1);
    }
    return 1;
}

这是写字符串非阻塞...

和。

第二个过程(#2)是......

int sign_receiver()
{
    int f , len;
    char temp_buffer[128]={0};

    f=open(PIPE_NAME,O_RDWR|O_NONBLOCK);
    if(f<0)
    {
        printf("open fail \n");
        exit(1);
    }

    while(1)
    {
        if((len=read(f,temp_buffer,sizeof(temp_buffer)))<0)
        {
            printf("read error. len = %d\n",len);
        }
        printf("read...\n");
        if(len>0)
        {
            printf("len : %d , sign process recv : [%s]\n",len,temp_buffer);
        }
        sleep(1);
    }

    close(f);
    unlink(PIPE_NAME);

    return 1;
} 

像这样。 进程(#1)首先运行。 和进程(#2)运行后5秒..

进程(#2)的 printf ....

read...
len : 15 , sign process recv : [hellohellohello]
read...
len : 5 , sign process recv : [hellohellohello]
read...
len : 5 , sign process recv : [hellohellohello]
read...
len : 5 , sign process recv : [hellohellohello]
read...
len : 5 , sign process recv : [hellohellohello]
read...
len : 5 , sign process recv : [hellohellohello]

我想要这个 printf。

read...
len : 5 , sign process recv : [hello]
read...
len : 5 , sign process recv : [hello]
read...
len : 5 , sign process recv : [hello]
read...
len : 5 , sign process recv : [hello]

我不知道为什么....我对 C 很陌生...

[hellohellohello]在第一次读取后一直被写入的原因是因为您没有在每次读取操作之间清除缓冲区。 因此,您在接下来的几行中实际看到的是:

len: 5, 签名过程recv: [hellohellohello]

是刚刚读取的消息hello ,并且覆盖了缓冲区先前 state 中包含的 5 个首字母,然后是缓冲区中剩余的内容,因此重复了消息。

以下是如何清除缓冲区的示例:

int sign_receiver()
{
    int f , len;
    char temp_buffer[128]={0};

    f=open(PIPE_NAME,O_RDWR|O_NONBLOCK);
    if(f<0)
    {
        printf("open fail \n");
        exit(1);
    }

    while(1)
    {
        if((len=read(f,temp_buffer,sizeof(temp_buffer)))<0)
        {
            printf("read error. len = %d\n",len);
        }
        printf("read...\n");
        if(len>0)
        {
            printf("len : %d , sign process recv : [%s]\n",len,temp_buffer);
            memset(temp_buffer, 0, 128); <- Adding this line
        }
        sleep(1);
    }

    close(f);
    unlink(PIPE_NAME);

    return 1;
}

但这不会让你摆脱第一个[hellohellohello] ,那是因为你在阅读之前在命名 pipe 上写了几次(在你的情况下是 3 次)。 这些消息被缓冲在系统缓冲区中,直到被读取调用检索。

您的非阻塞读取并不意味着它会丢弃积累在系统缓冲区中的堆积数据,它只是意味着它的调用将立即返回,即使没有读取任何数据。

如果您不想在第一次读取时添加消息,我建议您颠倒调用这两个进程的顺序,在可执行文件 1 之前运行可执行文件 2。

您还可以在消息中添加额外的定义,使用页眉/页脚或分隔符,让您在有效负载中解析消息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM