c - 在 c 中使用带有 fork 的 cd 命令

标签 c linux directory fork chdir

是否可以使用 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);
}

关于c - 在 c 中使用带有 fork 的 cd 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38579233/

相关文章:

c - 在 ubuntu 终端窗口中运行文件之前如何消除使用 "./"的需要?

r - 如何在基于rstudio ubuntu上轻松切换R版本?

java - 将 commons.io FileUtils.listFiles 替换为 nio

c - 如何释放结构体c中的双指针?

c - printf() 函数异常

c - 将数据写入 C 中另一个程序的指针?

linux - Linux套接字实现在哪里?

c - Linux编程: Writing to duplicated socket fails

c# - 有没有办法停止 Directory.GetFiles 搜索

linux shell脚本复制目录树和链接文件