diff -ruN postgresql-7.4.13-old/src/backend/storage/file/fd.c postgresql-7.4.13/src/backend/storage/file/fd.c
--- postgresql-7.4.13-old/src/backend/storage/file/fd.c	2005-08-07 20:48:00.000000000 +0200
+++ postgresql-7.4.13/src/backend/storage/file/fd.c	2006-08-05 17:24:05.000000000 +0200
@@ -50,6 +50,9 @@
 #include "storage/fd.h"
 #include "storage/ipc.h"
 
+#ifdef CHECK_RLIMIT_NOFILE
+#include <sys/resource.h>
+#endif
 
 /* Filename components for OpenTemporaryFile */
 #define PG_TEMP_FILES_DIR "pgsql_tmp"
@@ -278,15 +281,28 @@
 	int			used = 0;
 	int			highestfd = 0;
 	int			j;
+#ifdef CHECK_RLIMIT_NOFILE
+	struct rlimit	    rlim;
+#endif
 
 	size = 1024;
 	fd = (int *) palloc(size * sizeof(int));
 
+#ifdef CHECK_RLIMIT_NOFILE
+	getrlimit(RLIMIT_NOFILE, &rlim);
+#endif
+
 	/* dup until failure or probe limit reached */
 	for (;;)
 	{
 		int		thisfd;
 
+#ifdef CHECK_RLIMIT_NOFILE
+               /* Don't go beyond RLIMIT_NOFILE */
+		if (highestfd >= rlim.rlim_cur - 1)
+		    break;
+#endif
+
 		thisfd = dup(0);
 		if (thisfd < 0)
 		{
