Created
October 27, 2013 22:37
-
-
Save mpapierski/7188762 to your computer and use it in GitHub Desktop.
asynchronous I/O?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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