// Write a small program that calls fork and has the child create a new session. Verify that
// the child becomes a process group leader and that the child no longer has a controlling
// terminal

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
	int     pid;
	int     sid;
	int     gid;
	FILE    *file;

	if ((pid = fork()) < 0) {
		abort();
	} else if (pid == 0) {      /* child */
		// create a new session
		if ((sid = setsid()) < 0)
			puts("child 1");
		if (sid == getpid())
			puts("child 2");
		// verify that child becomes a process group leader
		gid = getpgrp();
		if (gid == getpid())
			puts("child 3");
		// check if child has a controlling terminal
		// try to open /dev/tty, open fails if has no controlling tty.
		// if ((fd = open("/dev/tty", O_RDWR)) == -1)
		if ((file = fopen("/dev/tty", "r+")) == NULL)
			puts("there is no controlling terminal.");
		puts("child 4");
		exit(0);
	}

	if ((file = fopen("/dev/tty", "r+")) == NULL)
	    printf("there is no controlling terminal.");
	puts("parent");

	exit(0);
}