/*
 * This is a test program for forked child early exit, if SIGCHLD
 * is being deivered reliable in nonRT and RT conditions.
 * It also tries to solve syslogging through signal handler via
 * an extra fork, which is signal handler safe.
 *
 * Author: Samo Pogacnik, 
 * Date: Jan, 2009
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <semaphore.h>
#include <signal.h>
#include <sched.h>
#include <time.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/ioctl.h>

#define SYSLOG 1
#define SEMSYNC 0
#define DAEMONIZE 0
#define RTPROC 0
#define YIELD 1
#define EXEC 1

int chld_fork(void);
void chld_handler (int signum);
int daemonize(void);
void sigsyslog(int priority, const char *format, ...);

#if SEMSYNC
sem_t semparent;
#endif

int chldexit = 0;
int countfork = 0;
int countchld = 0;

int main(int argc, char **argv)
{
	int i;
	struct sigaction actchld;
	struct sched_param sp;

#if SYSLOG /*add syslog*/
	openlog("forkchld", LOG_NDELAY | LOG_PID, LOG_USER);
#endif

#if DAEMONIZE /*daemonize*/
	daemonize();
#endif

#if RTPROC /*RT*/
	memset(&sp, 0, sizeof(struct sched_param));
        sp.sched_priority = 30;
	if (sched_setscheduler(0, SCHED_FIFO, &sp) == -1) {
		perror("scheduler initialization error (sched_setscheduler) - end of program");
		exit(1);
	}
#endif

#if SEMSYNC
	if (sem_init(&semparent, 0, 0) == -1) {
		perror("semaphore initialization error (sem_init) - end of program");
		exit(1);
	}
#endif

	actchld.sa_handler = chld_handler;
	if (sigemptyset(&actchld.sa_mask) == -1) {
		printf("sigaction structure initialization error (sigemptyset) - end of program\n");
		exit(1);
	}
	actchld.sa_flags = 0;

	if (sigaction(SIGCHLD, &actchld, NULL) == -1) {
		perror("signal handler initialization error (sigaction) - end of program");
		exit(1);
	}

	for (i = 0; i < 10; i++) {
		if (chld_fork() == -1) {
			break; /*chld_fork() returned error - finish*/
		}
	}

	printf("countfork = %d\n", countfork);
	printf("countchld = %d\n", countchld);
}

int chld_fork(void)
{
	pid_t pidchld;
	struct timespec semtout;

	if ((pidchld = fork()) == 0) { /*child*/
#if YIELD /*added*/
		sched_yield();
#endif
#if EXEC /*do additional exec*/
		execl("./forkchld.sh", "./forkchld.sh", "stop", NULL);
		perror("exec initialization error (execl) - end of program");
#endif
		_exit(0); /*end of child*/
	} else {
		if (pidchld == -1) { /*error*/
			exit(1); /*fork error - end of program*/
		} else { /*parent*/
			++countfork;
#if SYSLOG /*add syslog*/
			syslog(LOG_INFO, "child created (PID = %d)\n", pidchld);
#endif
#if SEMSYNC /*do a semaphore sync*/
#if 1 /*timed semaphore*/
			if (clock_gettime(CLOCK_REALTIME, &semtout) == -1) {
        			perror("could not get absolute time (clock_gettime) - end of program");
			        exit(1);
			}
			semtout.tv_sec += 5;
			while (sem_timedwait(&semparent, &semtout) == -1) { /*parent waits on semaphore*/
#else
			while (sem_wait(&semparent) == -1) { /*parent waits on semaphore*/
#endif
				switch (errno) {
				case EINTR: break;
				case ETIMEDOUT:
					printf("waiting on a semaphore timed out\n");
					return -1;
				default: 
					perror("semaphore processing error (sem_wait) - end of program\n");
					exit(1); /*semaphore processing error - end of program*/
				}
			}
#else /*do a busy loop*/
			while (chldexit == 0);
			chldexit = 0;
#endif
		}	
	}
	return 0;
}

void chld_handler(int signum)
{
	int status, count = 0;
	pid_t pid;

#if SYSLOG /*add syslog*/
		sigsyslog(LOG_INFO, "SIGCHLD received in PID = %d\n", getpid());
#endif

	while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
		++count;
	}

	countchld += count;

#if SEMSYNC /*do a semaphore sync*/
	if (sem_post(&semparent) == -1) { /*unlock the semaphore*/
		perror("semaphore processing error (sem_post) - end of program\n");
		exit(1); /*semaphore processing error - end of program*/
	}
#else /*do a busy loop break*/
	chldexit = 1;
#endif
}

int daemonize(void)
{
	int fd, pid;

	if (getppid() != 1) {            /* parent not the init process */
		/* Ignoring job control stop signals  */
#ifdef SIGTTOU
		signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTTIN
		signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTSTP
		signal(SIGTSTP, SIG_IGN);
#endif

		/* Disassociating the process from process group and controlling terminal */
		if ((pid = fork()) != 0) {
			exit(0);     /* parent process exits */
		}

		/* child stays alive */
#ifdef BSD
		setgrp(0, gettid ());
		if ((fd = open("/dev/tty", O_RDWR)) >= 0) {  /* open ctrl tty */
			ioctl(fd, TIOCNOTTY, 0);                 /* dissasociate from controlling terminal*/
			close(fd);
		}
#else     /* system V */
		setsid();   /* become a session and group process leader without controlling terminal */
#endif
	}

	/* Closing all opened file descriptors */
	for (fd = 0; fd < NOFILE; fd++) close(fd);

	/* Change current directory to root directory */
	chdir("/");

	/* Clear any inherited file mode creation mask */
	umask(0);

	/* Open standard file descriptors (STDIN, STDOUT and STDERR) again */
	fd = open("/dev/null", O_RDONLY); /* STDIN */
	fd = open("/dev/console", O_WRONLY); /* STDOUT */
	fd = open("/dev/console", O_WRONLY); /* STDERR */

	return 0;
}

void sigsyslog(int priority, const char *format, ...)
{
	va_list ap;
	pid_t pid;
	int status;
	static volatile int siglogchld = 0;

	if (siglogchld == 0) {
		siglogchld = 1;
		if ((pid = fork()) == 0) { /*child*/
			va_start(ap, format);
			vsyslog(priority, format, ap);
			va_end(ap);
			_exit(0);
		} else {
			if (pid == -1) { /*error*/
				; /*fork error - no logging*/
			} else { /*parent*/
				; /*do nothing*/
			}
		}
	} else {
		siglogchld = 0;
	}
}

