env.c

00001 /*
00002  * Copyright (c) 2005-2012 by KoanLogic s.r.l. - All rights reserved.
00003  */
00004 
00005 #include <sys/types.h>
00006 #include <sys/stat.h>
00007 
00008 #include <string.h>
00009 #include <stdlib.h>
00010 #include <stdio.h>
00011 
00012 #include <toolbox/env.h>
00013 #include <toolbox/carpal.h>
00014 #include <toolbox/misc.h>
00015 
00087 int u_env_init (const char *prefix, const char *cfile)
00088 {
00089     enum { BUFSZ = 1024 };
00090     struct stat sb;
00091     char line[BUFSZ], pcmd[BUFSZ], *val;
00092     FILE *pi = NULL;
00093 
00094     dbg_return_if (cfile == NULL || prefix == NULL, ~0);
00095 
00096     /* if 'cfile' does not exist bail out */
00097     dbg_err_sifm (stat(cfile, &sb) == -1, "%s", cfile);
00098 
00099     dbg_err_if (u_snprintf(pcmd, BUFSZ, ". %s 2>/dev/null && env", cfile));
00100 
00101     dbg_err_if ((pi = popen(pcmd, "r")) == NULL);
00102 
00103     while(fgets(line, BUFSZ-1, pi))
00104     {
00105         if(strncmp(line, prefix, strlen(prefix)) == 0)
00106         {
00107             line[strlen(line)-1] = 0;
00108             val = strchr(line, '=');
00109             if(!val)
00110                 continue; /* should never happen... */
00111             *val++ = 0;
00112             /* line is the name and val the value */
00113             dbg_err_if(setenv(line, val, 1));
00114         }
00115     }
00116 
00117     pclose(pi);
00118     return 0;
00119 err:
00120     U_PCLOSE(pi);
00121     return ~0;
00122 }
00123 
00134 const char *u_env_var (const char *name)
00135 {
00136     return getenv(name);
00137 }
00138 

←Products
© 2005-2012 - KoanLogic S.r.l. - All rights reserved