Skip to content

Instantly share code, notes, and snippets.

@szaydel
Created April 21, 2021 20:12
Show Gist options
  • Save szaydel/1c461254d1d98f3e7a1f99a107cb9504 to your computer and use it in GitHub Desktop.
Save szaydel/1c461254d1d98f3e7a1f99a107cb9504 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
fd_set rfds;
struct timeval tv;
int retval;
int fd1[2];
pid_t p;
if (pipe(fd1)==-1) {
perror("pipe");
return 1;
}
p = fork();
if (p < 0) {
perror("fork");
return 1;
}
// Parent process
if (p > 0) {
FD_ZERO(&rfds);
FD_SET(fd1[0], &rfds);
/* Wait up to three seconds. */
tv.tv_sec = 3;
tv.tv_usec = 0;
printf("tv before: %ld.%06ld\n", tv.tv_sec, tv.tv_usec);
retval = select(fd1[0]+1, &rfds, NULL, NULL, &tv);
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 three seconds.\n");
printf("tv after : %ld.%06ld\n", tv.tv_sec, tv.tv_usec);
return 0;
} else { // child process
sleep(1);
write(fd1[1], "Hello", strlen("Hello"));
close(fd1[1]);
exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment