cforkscanfchdirgetcwd

Change current working directory in child process in C


I have to write a program which generates child process than ends parent process and after that that created child process has to ask user to input new working directory, change it and print path to its new working directory. I wrote this, but scanf is not working ("It's not asking user to input something, program just ends) and the path is not changing... I've tried to set new directory to char *newdirectory="home/usr/desktop" and that didn't change working directory too

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>

int main()
{
    int pid;
    char directory[1024];
    char newdirectory[1024];        
    pid=fork(); 
    if(pid<0)
    {
        printf("\n Error ");
        exit(1);
    }
    else if(pid==0)
    {
        printf("I'm child \n ");
        printf(" My PID: %d \n",getpid());
        getcwd(directory, sizeof(directory));
        printf(" My current working directory is: %s\n", directory);
        printf(" Enter the new path\n");
        scanf("%s", &newdirectory);
        chdir(newdirectory);
        getcwd(directory, sizeof(directory));
        printf(" Path changed to: %s\n", directory);
        exit(0);
    }
    else
    {
        printf("I'm a parent \n ");
        printf("My PID is %d \n ",getpid());
        printf("Bye bye \n");
        exit(1);
    }
    return 0;
}

Thank you for your time, effort and all the help to understand :)


Solution

  • You have two mistakes,

    The following works.

    #include <unistd.h>
    #include <stdio.h>
    #include <errno.h>
    #include <stdlib.h>
    #include <sys/stat.h>
    
    int main()
    {
        int pid;
        char directory[1024];
        char newdirectory[1024];
        pid=fork();
        if(pid<0)
        {
            printf("\n Error ");
            exit(1);
        }
        else if(pid==0)
        {
            printf("I'm child \n ");
            printf(" My PID: %d \n",getpid());
            getcwd(directory, sizeof(directory));
            printf(" My current working directory is: %s\n", directory);
            printf(" Enter the new path\n");
            scanf("%1023s", newdirectory);
            chdir(newdirectory);
            getcwd(directory, sizeof(directory));
            printf(" Path changed to: %s\n", directory);
            exit(0);
        }
        else
        {
            wait(0);
            printf("I'm a parent \n ");
            printf("My PID is %d \n ",getpid());
            printf("Bye bye \n");
            exit(1);
        }
    }