Skip to content

Instantly share code, notes, and snippets.

@mpapierski
Created October 27, 2013 22:37
Show Gist options
  • Save mpapierski/7188762 to your computer and use it in GitHub Desktop.
Save mpapierski/7188762 to your computer and use it in GitHub Desktop.
asynchronous I/O?
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/select.h>
int
async_open(const char * filename, int flags)
{
// create pipe
int fds[2] = {0};
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0)
{
std::cerr << "unable to create socket pair" << std::endl;
return -1;
}
pid_t pid = ::fork();
if (pid == 0)
{
int open_file = open(filename, flags);
char buf[16] = {'1', 0};
if (write(fds[1], buf, 1) != 1)
{
std::cerr << "unable to write ready signal to a pipe" << std::endl;
}
::close(fds[1]);
::close(open_file);
std::exit(0);
}
else if (pid > 0)
{
return fds[0];
}
else
{
return -1;
}
}
int
main()
{
int fd = async_open("/dev/urandom", O_RDONLY);
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval tv = {0};
tv.tv_sec = 1;
while (true)
{
int result = ::select(fd + 1, &fds, NULL, NULL, &tv);
if (result < 0)
{
std::cerr << "select error" << std::endl;
break;
}
if (result == 0)
{
std::cout << "no data received" << std::endl;
continue;
}
if (FD_ISSET(fd, &fds))
{
std::cout << "tak" << std::endl;
FD_CLR(fd, &fds);
}
}
close(fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment