determining the real directory when using automounts

Mark J. Kilgard mjk at trout.rice.edu
Thu Feb 9 06:04:22 AEST 1989


The automount feature of Sun OS 4.O is an incrediably nice feature but it
has the annoying side effect of blurring what your current working
directory is.  Example:

uncle-bens:/marsh/mjk#1 -> pwd
/tmp_mnt/auto274a00144/mjk

It kind of makes it hard to know where you are.

The following short program will return the "real" path name when you use
automounts:

/*
 *  realpwd - returns the "real" name of a directory even when
 *    obscurred by automounting
 *
 *  by Mark Kilgard
 *   1/29/88
 */

#include <stdio.h>
#include <mntent.h>
#include <sys/param.h>
#include <string.h>

#define TMP_MNT_PREFIX "/tmp_mnt/"
#define MTAB "/etc/mtab"

char* real_getwd()
{
   static char cwd[MAXPATHLEN];
   char mnt_prefix[MAXPATHLEN];
   char mnt_suffix[MAXPATHLEN];
   int i;
   int j;
   char* ptr;
   FILE* mtab;
   struct mntent* mount;

   getwd(cwd);
   if(!strncmp(cwd,TMP_MNT_PREFIX,sizeof(TMP_MNT_PREFIX)-1)) {
      mtab=setmntent(MTAB,"r");
      if(mtab==NULL) {
         return(cwd);
      }
      mnt_prefix[0]='/';
      i=1;
      while(cwd[i]!='/') {
         mnt_prefix[i]=cwd[i];
         i++;
      }
      mnt_prefix[i]='/';
      i++;
      while(cwd[i]!='/' && cwd[i]!='\0') {
         mnt_prefix[i]=cwd[i];
         i++;
      }
      mnt_prefix[i]='\0';
      j=0;
      while(cwd[i]!='\0') {
         mnt_suffix[j]=cwd[i];
         i++;
         j++;
      }
      mnt_suffix[j]='\0';

      while((mount=getmntent(mtab))!=NULL) {
         if(!strcmp(mount->mnt_dir,mnt_prefix)) {
            ptr=strrchr(mount->mnt_fsname,':');
            if(ptr==NULL) {
               return(cwd);
            }
            ptr++;
            strcpy(mnt_prefix,ptr);
            strcat(mnt_prefix,mnt_suffix);
            return(mnt_prefix);
         }
      }
      return(cwd);
   }
   return(cwd);
}

main()
{
   printf("%s\n",real_getwd());
}

Extracting the routine may be useful.  Realize the routine stores the
result in a static area for each call.  Essentially the routine does a
lookup in /etc/mtab.

- Mark Kilgard <mjk at rice.edu>



More information about the Comp.sys.sun mailing list