#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
static char * id = "@(#)myenv.c - Alex Swinney";
static void ignoreEnv(); /*use case 'i' &&/|| case '-'*/
static void processArgs(char ** args,int argc); /*use the environment*/
static void printEnv();
static void removeArgs(int ind, int argc, char ** argv);
static char * fileName;
static char * arguments[50];
static status;
extern char ** environ;
int main(int argc, char ** argv)
{
int ign = 0,c;
status = 0;
fileName = argv[0];
while ((c = getopt(argc, argv, "i")) != EOF)
{
if(c=='i')
{
ignoreEnv();
ign = 1;
break;
}
if(c=='?')
{
char usage[100]="";
sprintf(usage,"USAGE: %s [ -i | - ] [ name=value ... ] [ utility [ arg ... ] ]\n",fileName);
status = write(STDOUT_FILENO,usage,100);
exit(1);
}
}
if(!ign && argc > optind)
if(strcmp(argv[optind],"-")==0)
{
ign = 1;
ignoreEnv();
}
processArgs(argv,argc);
printEnv();
exit(status);
}
void processArgs(char ** args,int argc)
{
int ind = optind;
int error;
while(ind<argc)
{
if(!strchr(args[ind],'='))
{
break;
}
else
{
error = putenv(args[ind]);
if(error)
{
char buf[50];
sprintf(buf,"%s:%s",fileName,args[ind]);
perror(buf);
}
ind++;
}
}
if(ind<argc)/*now, check if there are any additional arguments, if so, it has to be an executable*/
{
int err=0;
/*first, remove all previous arguments*/
removeArgs(ind+1, argc,args);
/*next, execute the executable*/
/*printf("before execvp arg = %s\n",args[ind]);*/
while(arguments[err])
{
printf("%s\n",arguments[err]);
err++;
}
err = execvp(args[ind],arguments);
if(err<0)
{
char errorb[100];
sprintf(errorb,"%s:%s",fileName,args[ind]);
perror(errorb);
}
}
}
/* HERE IS WHERE I *ATTEMPT* TO IGNORE THE ENVIRONMENT*/
void ignoreEnv()
{
int e=0;
while((environ[e]))
{
environ[e]="";
e++;
}
}
void removeArgs(int ind, int argc, char ** argv)
{
int d=0;
for(d=0;ind<argc;d++,ind++)
{
arguments[ind] = argv[ind];
printf("%s\n",arguments[ind]);
}
}
void printEnv()
{
int e=0;
while(environ[e])
{
printf("%s\n",environ[e]);
e++;
}
}
How to ignore the unix environment?
I am in a systems programming class (Unix), and have a project where I am to emulate 'env', called 'myenv'.
I can't for the life of me find anything about how to ignore the environment via the '-' and '-i' options that 'env' uses.
Also, I seem to be having trouble using execvp, nothing happens when the program hits that particular line of code:
This is being developed on SunOS 5.8, if that helps.
If anyone sees anything wrong with the above code, don't hesitate to let me know about it!
Thanks
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement