roverred
roverred

Reputation: 1921

Linux C: Using fork() child to change directory

I'm making a command shell where I'm using the child to change the directory of shell, but I can't get it to change an array's contents;

In the end it just prints the current directory instead of "/". The child has no effect on the newDirectory array. What am I doing wrong? Is there a way to make the child change the contents of the array? Thanks.

char newDirectory[255];

getcwd(newDirectory, 255); //set newDirectory to current directory

pid_t pid;      

pid = fork();

if(pid == 0){   //child execution       

    strcpy(newDirectory, "/");

    exit(0);
}

else if (pid < 0){                  
    printf( "Error!\n");    
    exit(1);
}
else{                       
     pid = waitpid(pid, NULL, 0);   
}
printf("%s\n", newDirectory);
chdir(newDirectory);

Upvotes: 1

Views: 5344

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126877

(moving from the comment)

When you do a fork() the new process is an independent copy1 of the parent, so whatever change you make to variables of the child isn't visible from the parent process - they have two independent virtual address spaces.

If you want the child process to communicate with the parent you have to use some IPC method (e.g. pipes, shared memory, sockets, ...).


  1. actually, on modern systems address space copying is actually implemented with copy on write, but that doesn't change the point.

Upvotes: 2

Sean Conner
Sean Conner

Reputation: 416

The easiest solution is not not use a child process to change the current working directory (because the current working directory will only change in the child process, not the parent, as stated by Matteo).

If you check existing shells (like bash or even sh) you will notice that some commands are considered "built-in" and cd is one such command.

Upvotes: 0

Related Questions