我有一个父进程和一个子进程,第二个进程是用 fork 创建的,子进程从父亲那里收到一个字符 s[](s 可以是类似“cd Music”的东西),我从“cd Music”中提取音乐使用 strtok,但是当 chdir(dir) 执行时,我得到“没有这样的文件或目录”。但是如果我测试 chdir("Music") 我不会出错。我想更改子进程的工作目录。请帮助我...
char *dir = strtok(s," ");
dir = strtok(NULL," ");
if(chdir(dir) == -1){
perror("Cannot change directory");
}
最佳答案
fork()之后父子之间就没有通信了。这(伪代码)不起作用:
int s[100];
if (fork()) {
/* father */
strcpy(s, "cd Music"); /* pass string to child -- NOT! */
/* ... */
} else {
/* use uninitialized s */
}
这行得通
int s[100] = "cd Music";
if (fork()) {
/* father */
/* ... */
} else {
/* use children's copy of s */
}
关于chdir 在 c 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4003574/