簡體   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