【问题标题】:How to "try" to read input in C如何“尝试”读取 C 中的输入
【发布时间】:2013-12-27 20:43:36
【问题描述】:

我正在编写一个允许在 Linux 中的两个进程之间聊天的程序。为了传输消息,我使用 IPC 队列。

我的主循环有问题:我需要检查队列中是否有任何新消息,如果有 - 打印它。然后我需要检查是否有任何输入,如果有 - scanf 它(这就是问题)。 有什么想法吗?

【问题讨论】:

  • 你不能在队列中阻塞吗?
  • 你对scanf有什么问题?

标签: c console chat


【解决方案1】:

使用非阻塞操作。如果对使用O_NONBLOCK 标志打开的文件描述符执行read(),并且此时没有可用数据,read() 将立即返回errno = -EWOULDBLOCK

另一种选择是使用select() 轮询多个描述符。

【讨论】:

  • select 既可以是轮询的,也可以是非轮询的,具体取决于超时时间。但默认情况下,它不会返回,直到受监视的描述符之一有数据要读取或可以接受写入(取决于参数)。当我需要等待输入时,我更喜欢select 方法。
  • 这正是我需要的,我会试试的
【解决方案2】:

为了给我的帖子增加更多价值,我粘贴了一个我找到的示例,它解决了我的问题

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    fd_set rfds;
    struct timeval tv;
    int retval;

    /* Watch stdin (fd 0) to see when it has input. */
    FD_ZERO(&rfds);
    FD_SET(0, &rfds);

    /* Wait up to five seconds. */
    tv.tv_sec = 5;
    tv.tv_usec = 0;

    retval = select(1, &rfds, NULL, NULL, &tv);
    /* Don't rely on the value of tv now! */

    if (retval == −1)
        perror("select()");
    else if (retval)
        printf("Data is available now.\n");
        /* FD_ISSET(0, &rfds) will be true. */
    else
        printf("No data within five seconds.\n");

    exit(EXIT_SUCCESS);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 2013-02-11
    • 2017-10-12
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多