//
// WILL NOT WORK ON ideone.com!!! COMPILE ON YOUR OWN LINUX MACHINE USING
//
// gcc -std=gnu11 -Wall -Wextra -Wconversion -Werror -pedantic -pedantic-errors -o prog prog.c
//
#include <alloca.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
void pputs(char const * const string) {
printf("%d(%d): ", getpid(), getppid());
puts(string);
}
int main() {
pputs(__FILE__);
pputs("reading from stdin [press Enter]");
assert(errno == 0);
read(STDIN_FILENO, alloca(0x100), 0x100);
assert(errno == 0);
pputs("forking");
if (fork()) {
// parent
sleep(1);
pputs("slept one second");
pputs("reading from stdin [should fail with EWOULDBLOCK]");
assert(errno == 0);
read(STDIN_FILENO, alloca(0x100), 0x100);
assert(errno == EWOULDBLOCK);
errno = 0;
pputs(strerror(EWOULDBLOCK));
} else {
// child
pputs("setting stdin to non-blocking");
int const flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
}
pputs("exiting");
exit(EXIT_SUCCESS);
}
Ly8KLy8gV0lMTCBOT1QgV09SSyBPTiBpZGVvbmUuY29tISEhIENPTVBJTEUgT04gWU9VUiBPV04gTElOVVggTUFDSElORSBVU0lORwovLwovLyBnY2MgLXN0ZD1nbnUxMSAtV2FsbCAtV2V4dHJhIC1XY29udmVyc2lvbiAtV2Vycm9yIC1wZWRhbnRpYyAtcGVkYW50aWMtZXJyb3JzIC1vIHByb2cgcHJvZy5jCi8vCgojaW5jbHVkZSA8YWxsb2NhLmg+CiNpbmNsdWRlIDxhc3NlcnQuaD4KI2luY2x1ZGUgPGVycm5vLmg+CiNpbmNsdWRlIDxmY250bC5oPgojaW5jbHVkZSA8c3RkaW8uaD4KI2luY2x1ZGUgPHN0ZGxpYi5oPgojaW5jbHVkZSA8c3RyaW5nLmg+CiNpbmNsdWRlIDxzeXMvdHlwZXMuaD4KI2luY2x1ZGUgPHVuaXN0ZC5oPgogCnZvaWQgcHB1dHMoY2hhciBjb25zdCAqIGNvbnN0IHN0cmluZykgewogICAgICAgIHByaW50ZigiJWQoJWQpOiAiLCBnZXRwaWQoKSwgZ2V0cHBpZCgpKTsKICAgICAgICBwdXRzKHN0cmluZyk7Cn0KIAppbnQgbWFpbigpIHsKCQlwcHV0cyhfX0ZJTEVfXyk7CiAgICAgICAgcHB1dHMoInJlYWRpbmcgZnJvbSBzdGRpbiBbcHJlc3MgRW50ZXJdIik7CiAgICAgICAgYXNzZXJ0KGVycm5vID09IDApOwogICAgICAgIHJlYWQoU1RESU5fRklMRU5PLCBhbGxvY2EoMHgxMDApLCAweDEwMCk7CiAgICAgICAgYXNzZXJ0KGVycm5vID09IDApOwogICAgICAgIHBwdXRzKCJmb3JraW5nIik7CiAgICAgICAgaWYgKGZvcmsoKSkgewogICAgICAgICAgICAgICAgLy8gcGFyZW50CiAgICAgICAgICAgICAgICBzbGVlcCgxKTsKICAgICAgICAgICAgICAgIHBwdXRzKCJzbGVwdCBvbmUgc2Vjb25kIik7CiAgICAgICAgICAgICAgICBwcHV0cygicmVhZGluZyBmcm9tIHN0ZGluIFtzaG91bGQgZmFpbCB3aXRoIEVXT1VMREJMT0NLXSIpOwogICAgICAgICAgICAgICAgYXNzZXJ0KGVycm5vID09IDApOwogICAgICAgICAgICAgICAgcmVhZChTVERJTl9GSUxFTk8sIGFsbG9jYSgweDEwMCksIDB4MTAwKTsKICAgICAgICAgICAgICAgIGFzc2VydChlcnJubyA9PSBFV09VTERCTE9DSyk7CiAgICAgICAgICAgICAgICBlcnJubyA9IDA7CiAgICAgICAgICAgICAgICBwcHV0cyhzdHJlcnJvcihFV09VTERCTE9DSykpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgICAvLyBjaGlsZAogICAgICAgICAgICAgICAgcHB1dHMoInNldHRpbmcgc3RkaW4gdG8gbm9uLWJsb2NraW5nIik7CiAgICAgICAgICAgICAgICBpbnQgY29uc3QgZmxhZ3MgPSBmY250bChTVERJTl9GSUxFTk8sIEZfR0VURkwsIDApOwogICAgICAgICAgICAgICAgZmNudGwoU1RESU5fRklMRU5PLCBGX1NFVEZMLCBmbGFncyB8IE9fTk9OQkxPQ0spOwogICAgICAgIH0KICAgICAgICBwcHV0cygiZXhpdGluZyIpOwogICAgICAgIGV4aXQoRVhJVF9TVUNDRVNTKTsKfQ==