Today, Tony Lambiris gleaned this insight:

> okay, maybe i am missing the point totally with structures. here is my code, let
> me know whats wrong with it:
> 
> struct utsname *host_uname;
> 
> host_uname = (struct utsname *)malloc(sizeof(struct utsname));
> uname(host_uname);
> 
> system_os = malloc(strlen(host_uname->sysname)+1);
> strncpy(system_os, (host_uname->sysname), sizeof(system_os));
> 
> system_os is type char *. i cant see anything wrong with this code, but then
> again ive never worked extensively with structs.

The first part is o.k. but does more than it needs to (malloc is
reletively slow and unnecessary here).  The second part is just
unnecessary, and a waste of storage, unless you need to keep the system
name for some reason but want to modify the copy.

I'd replace this with:

{
  struct utsname host_uname;

  if ( (uname( &host_uname ) ) == -1 ){
    printf( "I broke uname()!\n" );
    handle_error();  /* I made this up... you need to handle the error */
  }


  /* other code goes here */

}


Now, any time you want the system name, just access it as
host_uname.sysname in your code.  There's no need to allocate another
buffer for it, you've already got it in your structure.

Note that handling an error from the call to uname is a good idea, but
probably over-paraniod... the only error uname() supposedly returns
(according to the man page) is EFAULT, which only happens if host_uname is
"not valid" -- whatever that means.  So as long as you've declared
host_uname properly, you should be fine.

So, for example, if all you want to do is print the system name, this will
probably suffice:


  #include <stdio.h>
  #include <sys/utsname.h>

  void print_name( void )
  { 
    struct utsname host_uname;
  
    uname( &host_uname );
    printf( "My name is %s\n", host_uname.sysname );

  }


Which (on my system) does indeed print:

$ ./u
My name is Linux

        
-- 
Derek Martin
[EMAIL PROTECTED]


**********************************************************
To unsubscribe from this list, send mail to
[EMAIL PROTECTED] with the following text in the
*body* (*not* the subject line) of the letter:
unsubscribe gnhlug
**********************************************************

Reply via email to