【问题标题】:Why is fopen blocked when server has a running thread?为什么服务器有正在运行的线程时 fopen 会被阻塞?
【发布时间】:2018-11-06 18:03:22
【问题描述】:

当服务器打开管道进行读取并通过std::async启动线程时,客户端第一次可以打开管道进行写入,但如果客户端再次写入,客户端将被阻塞,直到线程结束,服务器可以fopen读取管道。 有什么想法吗?

【问题讨论】:

  • 试着阅读你的问题,就好像你还不知道问题是什么一样。你会发现你没有提供足够的信息让其他人理解它。另见How to Askminimal reproducible example

标签: multithreading pipe fopen


【解决方案1】:

为我令人困惑的描述道歉。这是sn-ps的代码。

服务器端:

#define FIFO_FILE   "/tmp/fifo"

    while (1)
    {

    char readbuf[25];

    FILE *file = fopen(FIFO_FILE, "r");
    fgets(readbuf, 25, file);
    std::queue<std::string>().swap(msg);

    msg.push(readbuf);

    while (!feof(file))
    {
        fgets(readbuf, 25, file);
        msg.push(readbuf);
    }

    std::cout << "message num: " << msg.size() << std::endl;
    std::future<void> ret = std::async (std::launch::async, command_process, std::ref(msg), std::ref(binfo));
    fclose(file);
    std::cout << "messages are being processed!\n";

    }

客户端:

int main(int argc, char *argv[])
{
    FILE *fp;

    if((fp = fopen(FIFO_FILE, "w")) == NULL) {
        perror("fopen \n");
        return -1;
    }

    fputs(argv[1], fp);
    fclose(fp);
    return 0;
}

服务器启动后,在 fgets 处等待。当客户端发送一个字符串到FIFO,服务端接收到这个字符串并存储在msg中, 然后传给线程command_process处理,服务器等待 在 fopen 获取更多信息。 但是如果客户端再次尝试发送消息,它将在客户端的 fopen 处被阻塞,直到服务器的线程完成处理,服务器继续接收客户端的消息。

我希望客户端不应该被阻止发送消息并且服务器应该立即接收消息,然后中止先前的消息以处理新消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多