Skip to content

Instantly share code, notes, and snippets.

@lboulard
Last active May 29, 2016 13:34
Show Gist options
  • Save lboulard/767237ee541fa8e5dd29faa9757b8c64 to your computer and use it in GitHub Desktop.
Save lboulard/767237ee541fa8e5dd29faa9757b8c64 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE /* for pipe2 support */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include <pthread.h>
static int p[2];
static void *
closep0(void *arg) {
(void)arg;
sleep(1);
close(p[0]);
return NULL;
}
static void *
closep1(void *arg) {
(void)arg;
struct timespec t = { 0, 500 * 1000000L };
nanosleep(&t, NULL);
close(p[1]);
return NULL;
}
int
main(int argc, char **argv)
{
static char buf[16];
int i, r, opt, closed;
pthread_t tid[2] = {0};
closed = 1;
while ((opt = getopt(argc, argv, "k")) != -1) {
switch (opt) {
case 'k':
closed = 0;
break;
default:
fprintf(stderr, "Usage: %s [-k]\n", argv[0]);
fprintf(stderr, "\nOptions:\n\t-k to prevent closing write pipe.\n");
exit(EXIT_FAILURE);
}
}
if (pipe2(p, O_CLOEXEC) != 0) {
perror("pipe2");
exit(EXIT_FAILURE);
}
if ((r = pthread_create(tid + 0, NULL, closep0, NULL)) != 0) {
errno = r;
perror("phtread_create");
exit(EXIT_FAILURE);
}
if (closed && (r = pthread_create(tid + 1, NULL, closep1, NULL)) != 0) {
errno = r;
perror("phtread_create");
exit(EXIT_FAILURE);
}
r = read(p[0], buf, sizeof(buf));
if (r < 0)
perror("pipe read");
else if (r == 0)
puts("Pipe closed");
else
printf("what ??? r=%d\n", r);
for (i = 0; i < 2; i++) {
if (tid[i] && (r = pthread_join(tid[i], NULL)) != 0) {
errno = r;
perror("phtread_join");
exit(EXIT_FAILURE);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment