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

int pid_child;

// TODO: signal handler (used for SIGCHLD)


int main(int argc, char **argv) {
	unsigned int p = 0, n = (argc == 2) ? atoi(argv[1]) : 50;
	// TODO: install signal handler


	fflush(stdout);
	pid_child = fork();
	if (pid_child == 0) {
		// child process; do some work
		n *= 10000000;
		while(p++ < n)
			if (!(p%(n/10))) printf("CHILD process: working progress %d%% done\n", p/(n/100));
		p /= 10000000;
		printf("CHILD process: finished, exit code set to: %d\n", p);
		exit(p);

	} else if (pid_child > 0) {
		// parent process
		printf("PARENT: new child process created with pid %d\n", pid_child);
		printf("PARENT: start working\n");
		while(p++ < n*1000000000);	// do some work while signal is comming
		wait(NULL);     // this may fail, it only waits if parrent finishes work before the child
		printf("PARENT: finished\n");

	 } else {
		perror("PARENT: fork() error: ");
		exit(1);
	}

	return 0;
}
