Im writing a program which allows to chat between two processes in Linux. To transfer messages I use IPC queues.
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). 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
.
Another option is to use select()
to poll more than one descriptor.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.