Search code examples
clinuxforkchildren

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);

Solution

  • (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.