determine the max number of open file descriptor

1. header file + sysconf + guess code

2. use dup() function it

#include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>

#ifdef OPEN_MAX
static long openmax = OPEN_MAX;
#else
static long openmax = 0;
#endif

#define OPEN_MAX_GUESS 256

long
open_max(void)
{
	if (openmax == 0) {
		errno = 0;
		if ((openmax = sysconf(_SC_OPEN_MAX)) < 0) {
			if (errno == 0)
				openmax = OPEN_MAX_GUESS;
			else {
				perror("sysconf error for _SC_OPEN_MAX");
				exit(EXIT_FAILURE);
			}
		}
	}
	return openmax;
}

long
open_max_with_dup(void)
{
	int oldfd, fd;
	while ((fd = dup(0)) >= 0)
		oldfd = fd;
	if (errno == EMFILE)
		return (long)(oldfd+1);
	else {
		perror("dup failed");
		return -1;
	}
}

int
main(void)
{
	long openmax1, openmax2;
	openmax1 = open_max();
	openmax2 = open_max_with_dup();
	printf("openmax1=%ld \t openmax2=%ld \n", openmax1, openmax2);
	return 0;
}
相關文章
相關標籤/搜索