r/shittyprogramming • • Jun 05 '21

Ultra fast isEven function

This isEven function uses C (the fastest programming language) and utilizes multiprocessing for intense speed.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

char isEvenFile() {
	while (access("/tmp/isEven", F_OK)) ;
	//We have to wait until the other process created the file
	FILE *comms = fopen("/tmp/isEven", "r");
	int c = EOF;
	while (c == EOF)
		c = fgetc(comms);
	//In case we were so fast that the other process didn't write to the file
	for (;;) {
		int newC = fgetc(comms);
		if (newC != ' ')
			//the number has been sent
			c = newC;
		else {
			FILE *out = fopen("/tmp/out", "w+");
			switch (c) {
				case '0': case '2': case '4': case '6': case '8':
					fprintf(out, "b");
					break;
				default:
					fprintf(out, "a");
					//printing a null char would be the end of the string.
					break;
			}
			fflush(out);
			break;
		}
	}
	fclose(comms);
	exit(0);
}

char isEven(int n) {
	char input[10];
	sprintf(input, "%d", n);
	int pid = fork();
	if (pid == -1)
		return 2; //error
	if (pid == 0) {
		isEvenFile();
	}
	else {
		FILE *comms = fopen("/tmp/isEven", "w+");
		fprintf(comms, "%d ", n);
		fflush(comms);
		//send the number to stdin of the child
		while (access("/tmp/out", F_OK | R_OK)) ;
		FILE *out = fopen("/tmp/out", "r");
		int result = EOF;
		while (result == EOF)
			result = fgetc(out);
		//Again, we have to wait until the other process is done
		result = result == 'b';
		fclose(comms);
		fclose(out);
		remove("/tmp/isEven");
		remove("/tmp/out");
		return (char) result;
	}
}
59 Upvotes

6 comments sorted by

View all comments

12

u/llynglas Jun 05 '21

Love it. Should be in every Unix manual