/*========================================================================
 * Copyright (C) GemTalk Systems 1986-2014.  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 32752 2014-02-28 22:11:10Z stever $
 *
 *========================================================================
 */

#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 = %d\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 = %d\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 %ld \n", i);
        printf("filename = %s\n", fileName); 
        printf("errno = %d\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 %ld \n", i);
      i = i + 1;
      }
    return 0;
}

