[LCP]array of struct with 1 element

Roberto Diaz rdiazmartin at vivaldi.dhis.org
Tue Sep 4 02:34:05 UTC 2001


> 1. How do I implement closeall() which closes all open
> file descriptors in ANSI C?? The problem can be broken
> down to how do I know which all files are open?

Well this is not easy to do.. I mean this is not portable if you want to
close just the *open* file descriptors.. you can know how many opened
filde descriptors you have looking at the /proc file system.. 

The way to make this in a posix portable way is to get the maximun number
of file descriptors an close all (it is supposed you dont do this too much
time in your program)

(this is according R. Stenvens) this function will guess the maximun
number or file descriptors your sytem allows to be open.

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

#define OPEN_MAX_GUESS 255 

int 
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")
			   /* exit or return error code */
			}
		}
	return openmax;
}

you can then close all..  (closing a non-open file descriptor only causes
close(2) to return an error and set errno to EBADF)

The problem here is that if your system dont have the _SC_OPEN_MAX and 
your system doesnt defines the OPEN_MAX value then you have to use the
guessed value.. which maybe is not the real value. 

> 2. Many time in kernel I find them using array of
> struct with 1 member.Example from fs.h
> struct files_struct files[1];

This is a way to declare a "pseudopointer" it is widely used in IP
implementations, the trick is the following:

Suppose you have a bunch of raw data in some pool of memory and that you
know that raw data contains structured data:

struct example {
	int len;
	unsigned char data[0];
};

then you can do this:

struct example *a = ( struct example *) raw_buffer;

now you can access the data this way

for (i = 0; i < a->len; < i++)
	do_whatever (a->data[i]);

you never overwrite other data since you are always into the raw buffer.
 

---
Roberto Diaz <rdiazmartin at vivaldi.dhis.org>
..For a Brave GNU World..    
                                        Concerto Grosso Op. 3/8 A minor
                        Antonio Vivaldi (so... do you need beautiful words?)
                                                                      -----




More information about the linuxCprogramming mailing list