/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/


#include	<unistd.h>
#include	<sys/resource.h>
#include	<sys/types.h>
#include	<sys/time.h>
#include	<sys/param.h>
#include	"utils.h"
#include	"limits.h"

void
_print_rlim(int type)
{
int er;
struct rlimit r;
	er = getrlimit(type,&r);
	if ( er < 0 ) {
		fprintf(stderr,"%i\t",type);
		perror("");
	}
	else {
		fprintf(stderr,"%i :\t%i - %i\n",
			type,
			r.rlim_cur,
			r.rlim_max);
	}
}

unsigned int
_get_mem_size()
{
static unsigned int mem_size;
int p[2];
int id;
char buf[100];
char * ptr;
int er;
unsigned int ret;
struct rlimit rr;

	if ( mem_size )
		return mem_size;
	pipe(p);
	id = fork();
	if ( id == 0 ) {
		close(1);
		dup(p[1]);
		close(p[0]);
		for ( id = 3 ; id <= sys_param.max_fd ; id ++ )
			close(id);
		system("prtconf | egrep Memory");
		exit(0);
	}
	close(p[1]);
	er = read(p[0],buf,100);
	close(p[0]);
	if ( er < 0 )
		return 100000000;
	buf[er] = 0;
	for ( ptr = buf ; *ptr ; ptr ++ )
		if ( '0' <= *ptr && *ptr <= '9' )
			break;
	ret = atoi(ptr);
	for ( ; *ptr && *ptr != ' ' ; ptr ++ );
	for ( ; *ptr && *ptr == ' ' ; ptr ++ );
	if ( strcmp(ptr,"Megabytes\n") == 0 )
		ret *= 1024*1024;
	else if ( strcmp(ptr,"Gigabytes\n") == 0 )
		ret *= 1024*1024*1024;
	getrlimit(RLIMIT_DATA,&rr);
	if ( ret > (unsigned int)rr.rlim_max )
		ret = rr.rlim_max;
	mem_size = ret;
	return ret;
}
