Toys: cpusoak and memsoak

Useful for using up CPU time and Memory,

cpusoak.c

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

int
main(int argc, char **argv)
{
	int children = argc > 1 ? atoi(argv[1]) : 1;

	while (children--) {
		pid_t pid = fork();
		if (!pid) {
			long n, i = 0;
			while (1) {
				n = ++i;
				while (n != 1) n = (n % 2) ? n * 3 + 1 : n / 2;
			}
		}
	}

	while (-1 != wait(NULL) && ECHILD != errno);

	return 0;
}

memsoak.c

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

int
main(int argc, char **argv)
{
	int children = argc > 1 ? atoi(argv[1]) : 1;
	int bytes = argc > 2 ? atoi(argv[2]) : 1024;
	int nap = argc > 3 ? atoi(argv[3]) : 3;

	while (children--) {
		pid_t pid = fork();
		if (!pid) {
			while (1) {
				malloc(bytes);
				sleep(nap);
			}
		}
	}

	while (-1 != wait(NULL) && ECHILD != errno);

	return 0;
}

Tags: , ,

Leave a comment