Esempio n. 1
0
int
main() {
	/* read and write pipes file descriptions, from the perspective of the parent process */
	int writePfd[2], readPfd[2];
	long childPid;

	/* create read and write pipes */
	if (pipe(writePfd) == -1)
		pexit("pipe");

	if (pipe(readPfd) == -1)
		pexit("pipe");

	childPid = fork();

	switch (childPid) {
	case -1:
		pexit("fork");
	case 0:
		/* child process: closes the write end of the write pipe, and the read end of the read pipe. */
		if (close(writePfd[1]) == -1)
			pexit("close write end of write pipe - child");

		if (close(readPfd[0]) == -1)
			pexit("close read end of read pipe - child");

		childLoop(writePfd[0], readPfd[1]);

		/* child loop is finished: this means that the parent process received EOF,
		 * and the write end of writePfd was closed */
		_exit(EXIT_SUCCESS);

	default:
		/* parent process: closes the read end of the write pipe, and the write end of the read pipe */
		if (close(writePfd[0]) == -1)
			pexit("close read end of write pipe - parent");

		if (close(readPfd[1]) == -1)
			pexit("close write end of read pipe - parent");

		parentLoop(readPfd[0], writePfd[1]);

		/* EOF received. Close write end of writePfd */
		if (close(writePfd[1]) == -1)
			pexit("close write end of write pipe - parent");

		printf("\n");
	}

	/* parent: wait for the child to die and terminate */
	wait(NULL);
	exit(EXIT_SUCCESS);
}
Esempio n. 2
0
/* Daemonize */
void
detach(void)
{
	int             pid;

	pid=fork();

	switch(pid) {
		case -1:
			perror("fork");
			exit(1);
			break;
		case 0:
			childLoop();
			break;
		default:
			exit(0);
	}
}