繁体   English   中英

在C中使用cd命令与fork

[英]Using cd command with fork in c

是否可以使用fork命令更改目录? 无需过多介绍我的代码,我可以做到以下几点:

childpid = fork();

if (childpid >= 0)
{
    if (childpid == 0)
    {   
        ret = execvp(argv[0],argv);
        exit(ret);    
    } else {

          waitpid(childpid,&status,0);
          ret = WEXITSTATUS(status);
    }
}

当我输入lspwd等基本命令时,上面的方法工作正常。是否可以实现使用cd函数的方法? 我可以键入命令cd ..但它什么也没做。

例如,如果我的程序位于/Users/username/Desktop/我想使用诸如cd ..命令进入/Users/username/或直接进入/Users

我已经看到了有关chdir一些信息,但是我不确定它是如何工作的/如何使用。

正如您提到的chdir是更改当前进程的工作目录的最佳方法,shell命令cd只会更改运行该命令的进程(而不是父进程)的工作目录,因为fork会创建一个新进程。

对于chdir的使用,您可以尝试:

#include <stdio.h>
#include <unistd.h>
int main() {
    char cwd[4096];
    fputs(getcwd(cwd,4096),stdout); // will print the current working directory
    fputs("\n",stdout); 
    chdir("/"); // change directory
    fputs(getcwd(cwd,4096),stdout); // print new working directory
    fputs("\n",stdout);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM