mem2swap.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Fri, 27 Dec 2013 16:00:09 +0100
changeset 167 7c6b221900bf
parent 139 cb1d3f4cf18e
child 169 df7c720bcaa6
permissions -rw-r--r--
Proper Datatypes to leave the 80's

/**
 * mem2swap.c
 * Copyright (C) 2008 Markus Broeker
 *
 * mem2swap usage: mem2swap [<MB>]
 */

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

#define N 1000

#ifndef DEFAULT_MEGS
#define DEFAULT_MEGS 64
#endif

#ifdef __linux__
#define CMD_FREE "/usr/bin/free"
#define CMD_ARGS "-m"
#elif __unix__
#define CMD_FREE "/sbin/sysctl"
#define CMD_ARGS "hw.usermem"
#endif

int set_limit (int);

int main (int argc, char **argv)
{
    int i, n = 0;

    unsigned long *p;
    unsigned long *p_new;

    char *args[] = { CMD_FREE, CMD_ARGS, NULL };

    unsigned long size = sizeof (*p);
    int megs = DEFAULT_MEGS;
    int pid;

    if (argc == 2)
        megs = atoi (argv[1]);

    printf ("Mem2Swap - Version 1.0\n");

    if (!set_limit (megs))
        printf ("%d MB demanded ", megs);
    else {
        printf ("\tUsage: %s [MEM]\n\n", argv[0]);
        printf ("Report bugs to mbroeker@largo.homelinux.org\n");

        perror ("Limit Error");
        return EXIT_FAILURE;
    }

    if ((p = malloc (N * size)) == NULL)
        return EXIT_FAILURE;

    for (;;) {
        for (i = 0; i < N; i++)
            p[n * N + i] = size * (n * N + i);
        if ((p_new = realloc (p, (++n + 1) * N * size)))
            p = p_new;
        else
            break;
    }

    if (p) {
        printf ("and %ld MB allocated\n", p[n * N - 1] / 1024 / 1024);
        free (p);
    }

    printf ("\n\n");

    pid = fork ();
    switch (pid) {
    case 0:
        execve (CMD_FREE, args, NULL);
        exit (EXIT_FAILURE);
    case -1:
        perror ("Fork Error");
        return EXIT_FAILURE;
    default:
        wait (&pid);
    }

    return pid;
}