简体   繁体   English

如何“尝试”读取C语言中的输入

[英]How to “try” to read input in C

Im writing a program which allows to chat between two processes in Linux. 我正在编写一个程序,该程序允许在Linux中的两个进程之间进行聊天。 To transfer messages I use IPC queues. 要传输消息,我使用IPC队列。

I have a problem with main loop: I need to check if there's any new message in the queue and if there is - print it. 我的主循环有问题:我需要检查队列中是否有任何新消息,以及是否有-打印它。 Then I need to check if there is any input, and if there is - scanf it (this is the problem). 然后,我需要检查是否有任何输入,以及是否有-scanf(这是问题)。 Any ideas? 有任何想法吗?

Use non blocking operations. 使用非阻塞操作。 If a read() is performed on a file descriptor opened with O_NONBLOCK flag, and there's no data available at that moment, read() will return inmediately with errno = -EWOULDBLOCK . 如果对使用O_NONBLOCK标志打开的文件描述符执行read() ,并且此时没有可用数据,则read()将以errno = -EWOULDBLOCK返回。

Another option is to use select() to poll more than one descriptor. 另一种选择是使用select()轮询多个描述符。

to add more value to my post I'm pasting an example I found, which solves my problem 为我的帖子增加更多价值,我正在粘贴一个发现的示例,它解决了我的问题

#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);
}

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

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