#include "unistd.h"
#include "fcntl.h"
#include "stdlib.h"
#include "sys/select.h"
#include "stdio.h"

int main() {
	int master_fd = posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK);
	char* slave_name = ptsname(master_fd);
	unlockpt(master_fd);
	grantpt(master_fd);
	printf("master_fd = %d, slave = %s\n", master_fd, slave_name);

	// If omitted, select will start returning immediately without setting master_fd in fds after a client opens and closes slave ttys once
	int slave_fd = open(slave_name, O_RDONLY);

	fd_set fds;
	FD_ZERO(&fds);

	while (1) {
		FD_SET(master_fd, &fds);

		int ret = select(master_fd+1, &fds, NULL, NULL, NULL);
		printf("select ret = %d ", ret);
		if (FD_ISSET(master_fd, &fds)) {
			char c = 0;
			int r = read(master_fd, &c, 1);
			printf("r = %d, c = '%c'\n", r, c);
			write(master_fd, &c, 1);
		} else {
			printf("master_fd is not set in fds\n");
		}
	}

	return 0;
}