【问题标题】:chdir doesn't work in cchdir 在 c 中不起作用
【发布时间】:2010-10-23 10:46:26
【问题描述】:

我有一个父进程和一个子进程,第二个是用 fork 创建的,子进程从父亲那里收到一个 char 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");    
}

【问题讨论】:

    标签: c posix chdir


    【解决方案1】:

    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 */
    }
    

    【讨论】:

      【解决方案2】:

      尝试打印出 dir 的内容。也许它的价值不是你所期望的。

      【讨论】:

      • 或使用gdb 或任何可用的调试器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      相关资源
      最近更新 更多