Daniel
Daniel

Reputation: 11

chdir doesn't work in c

I have a father process and a child process, the second created with fork, the child receive from the father a char s[] (s can be something like "cd Music" ), i extract Music from "cd Music" using strtok, but when chdir(dir) executes i get "No such file or directory". But if i test chdir("Music") i get no error. I want to change the working directory of the child process. Help me please...

 char *dir  = strtok(s," ");
 dir = strtok(NULL," ");
 if(chdir(dir) == -1){
    perror("Cannot change directory");    
}

Upvotes: 1

Views: 1417

Answers (2)

pmg
pmg

Reputation: 108938

There is no communication between the father and the child after the fork(). This (pseudo code) doesn't work:

int s[100];
if (fork()) {
    /* father */
    strcpy(s, "cd Music"); /* pass string to child -- NOT! */
    /* ... */
} else {
    /* use uninitialized s */
}

This works

int s[100] = "cd Music";
if (fork()) {
    /* father */
    /* ... */
} else {
    /* use children's copy of s */
}

Upvotes: 3

tangrs
tangrs

Reputation: 9930

Try printing out the contents of dir. Maybe its value is not what you expected.

Upvotes: 0

Related Questions