#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

#include <sys/stat.h>
#include <sys/types.h>

#define DEV_PTS_MNT	"/dev/pts"
#define FILE_NAME	"ptmx"

static void *readdir_thread(void *arg)
{
	DIR *d = (DIR *)arg;
	struct dirent *dent;

	while (1) {
		errno = 0;
		dent = readdir(d);
		if (!dent) {
			if (errno)
				perror("readdir");
			break;
		}
		rewinddir(d);
	}

	return NULL;
}

int main(void)
{
	DIR *d;
	pthread_t t;
	int ret = 0;

	d = opendir(DEV_PTS_MNT);
	if (!d) {
		ret = errno;
		perror("opendir");
		return ret;
	}

	ret = pthread_create(&t, NULL, readdir_thread, d);
	if (ret) {
		errno = ret;
		perror("pthread_create");
		return ret;
	}

	while (1) {
		int fd = openat(dirfd(d), FILE_NAME, O_RDONLY | O_NONBLOCK);
		if (fd < 0) {
			perror("openat");
			break;
		}
		close(fd);
	}

	pthread_join(t, NULL);
	ret = closedir(d);
	if (ret)
		perror("closedir");

	return ret;
}
