/*========================================================================
 * Copyright (C) VMware, Inc. 1986-2011.  All Rights Reserved..
 *
 * Name - fileopentest.c 
 * Description: 
 *   example program to test how many files can be simultaneously 
 *   opened by a process .  
 *
 *   For SunOs only
 *
 * $Id: fileopentest.c,v 1.6 2008-01-09 22:50:49 stever Exp $
 *
 *========================================================================
 */

#if defined(__hpux)
#if !defined(_HPUX_SOURCE)
#define _HPUX_SOURCE
#endif /* !defined(_HPUX_SOURCE) */
#include <sys/stdsyms.h> /* Pick up the other related #defs */
#endif

#include <errno.h>
#include <stdio.h>

#include <sys/time.h>
#include <sys/resource.h>

#include <unistd.h>

#if defined(hpux) || defined(__hpux) || defined(sparcSolaris) || defined(i386)
#define getdtablesize() sysconf(_SC_OPEN_MAX)
#endif

#include <sys/types.h>

void printLimits(void)
{   
    struct rlimit limStruct;
    long rlimResult;

    rlimResult = getrlimit(RLIMIT_NOFILE, &limStruct);
    if (rlimResult != 0) {
      printf("getrlimit returned %ld\n", rlimResult);
      printf("errno = %ld\n", errno);
      perror("host error text = ");
      }
    else
      printf("getrlimit returns:  rlim_cur = %ld, rlim_max = %ld\n", 
                       limStruct.rlim_cur, limStruct.rlim_max);
    printf("getdtablesize returns  %ld\n", getdtablesize() );
}

int main (int argc, char *argv[])
{
    long i, fileLimit ;
    char fileName[100];
    long myPid;
    struct rlimit limStruct;
    long rlimResult;

    myPid = getpid();

    printLimits();
    limStruct.rlim_cur = RLIM_INFINITY;
    limStruct.rlim_max = RLIM_INFINITY;
    printf("Now calling setrlimit to request max possible file descriptors.\n");
    rlimResult = setrlimit(RLIMIT_NOFILE, &limStruct);
    if (rlimResult != 0) {
      printf("setrlimit returned %ld\n", rlimResult);
      printf("errno = %ld\n", errno);
      perror("host error text = ");
      }
    printLimits();
    fileLimit = limStruct.rlim_cur - 5; 
    i = 1;
    while (i < fileLimit) {
      sprintf(fileName, "/tmp/fileopen%ld_%ld.out\0",myPid, i);  
      if ( fopen(fileName, "w" ) == NULL ) {
        printf("Failed on file %d \n", i);
        printf("filename = %s\n", fileName); 
        printf("errno = %ld\n", errno);
        perror("host error text = ");
        if (i == 1)
          printf("You may need to  mkdir ./temp \n");
	return 1;
        }
      if ((i % 25) == 0) 
        printf("successfully opened file %d \n", i);
      i = i + 1;
      }
    return 0;
}

