【问题标题】:FIFO files and read/writeFIFO 文件和读/写
【发布时间】:2013-01-05 15:32:38
【问题描述】:

我在周一的实验室之前一直试图了解 FIFO 和这种低级 I/O,但我遇到了我不太了解的情况。

程序应该:

服务器:

  • 创建 FIFO,
  • 发送 5 条消息:“消息 #i”,间隔为 5 秒,
  • 删除 FIFO,

客户:

  • 从 FIFO 读取并显示消息,
  • 如果 6 秒内没有消息则终止,

但它确实进行了通信,客户端显示的并不完全是我发送给他的内容,更重要的是,每次新消息到达时似乎都从头开始读取。我一直在试图弄清楚,很长一段时间,它似乎与文档所说的不符......请帮忙! :(

服务器

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>  
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char* argv[])
{       
    int s2c, c2s, i; 
    char fifo_name1[] = "/tmp/fifo1";
    char fifo_name2[] = "/tmp/fifo2";
    char msg[80], buf[10];
    struct stat st;

    // if no fifos, create 'em
    if (stat(fifo_name1, &st) != 0)
        mkfifo(fifo_name1, 0666);
    if (stat(fifo_name2, &st) != 0)
        mkfifo(fifo_name2, 0666);

    s2c= open(fifo_name1, O_WRONLY);
    c2s= open(fifo_name2, O_RDONLY);

    // start sending messages, with 5s interval
    for (i=0; i<5; i++)
    {
        printf("Message #%d \n", i);

        strcat(msg, "Message #"); 
        strcat(msg, itoa(i, buf, 10));
        strcat(msg, "\0"); 

        write(s2c, msg, strlen(msg)+1);

        sleep(5);
    }

    // delete fifos
    unlink(fifo_name1);
    unlink(fifo_name2);
    printf("server exit successfully");
    return EXIT_SUCCESS;
}

客户

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    int c2s, s2c, c=0;
    char buf[10];

    char fifo_name1[] = "/tmp/fifo1";
    char fifo_name2[] = "/tmp/fifo2";
    s2c= open(fifo_name1, O_RDONLY);
    c2s= open(fifo_name2, O_WRONLY);

    // receive messages
    while (1)
    {
        if (read(s2c, &buf, sizeof(char)*10) > 0)
        {
            printf("%s \n", buf);
            c=0;
        }
        sleep(1);
        c++;    
        if (c>6) 
            break;
    }

    printf("client exit successfully");
    return EXIT_SUCCESS;
}       

【问题讨论】:

    标签: c linux fifo


    【解决方案1】:

    strcat(msg, "Message #"); 总是附加到 msg 中已经存在的字符串的末尾,并且在循环期间永远不会重置字符串。将其替换为 strcpy(msg, "Message #"); 以从头开始每条新消息。

    【讨论】:

    • 非常感谢,现在可以使用了! :D 看起来我在一个完全错误的地方寻找错误,真丢脸:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    相关资源
    最近更新 更多