I have a program, my own shell where the first input is command and the 2nd is cmd. Im trying to get cd working but having trouble with chdir function, i have this and it just gives me a segmentation fault and i dont understand why.

while(!strcmp(command,"cd")) // while the first command is cd do the following
			{
				if(strcmp(cmd,NULL) == 0) //if the 2nd command is null then change cd to home
				{
					chdir(getenv("HOME"));
				}
				else // if the 2nd command isnt a null then change directory to whatever the 2nd command says.
				{
					chdir(cmd);
				}

any help?
}

> if(strcmp(cmd,NULL) == 0)
Well this will blow up every time!

Perhaps you meant to test cmd for being empty?

> chdir(getenv("HOME"));
getenv() might return NULL as well, and that will segfault as well.

> if(strcmp(cmd,NULL) == 0)
Well this will blow up every time!

Perhaps you meant to test cmd for being empty?

> chdir(getenv("HOME"));
getenv() might return NULL as well, and that will segfault as well.

Ok got rid of the one that will blow up, easy enough,

then changed the if statement that blows up to

if (x = 1) 	if(cmd == NULL)
			{
				x = 1;
				
			}
			printf("\nx = %d\n\n", x);
			while(!strcmp(command,"cd")) 
			{
				if(x = 1)
				{
					chdir(getenv("HOME"));
				}
				else
				{
					chdir(cmd);
				}
			}

just done now another way of changing the getenv,

Now your code makes no sense at all.
Did you just type that in as a reply, or actually test it?

forget the first if (x = 1) on line 1 didnt mean to type that.

Basically what im doing, is testing if cmd is null or not, if it is im giving x to 1, if not then x remains 0, so then i do if cmd is null (by doing a if ( x == 1) then just do cd home. else do cd then pathname.

yes iv tested it , stops the seg fail but now just does nothing.

this is what i have in my code

if(cmd == NULL)
			{
				x = 1;
				
			}
			printf("\nx = %d\n\n", x);
			while(!strcmp(command,"cd")) 
			{
				if(x == 1)
				{
					chdir(getenv("HOME"));
				}
				else
				{
					chdir(cmd);
				}
			}

Edited 6 Years Ago by phil750: n/a

This article has been dead for over six months. Start a new discussion instead.