【问题标题】:Using cd command with fork in c在c中使用带有fork的cd命令
【发布时间】:2016-07-26 00:13:17
【问题描述】:

是否可以使用 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 的资料,但我不确定它是如何工作的/如何使用它。

【问题讨论】:

  • 当前目录特定于每个进程。所以你的shell进程在/Users/username/Desktop中,你输入cd ..,这会创建一个新进程,新进程更改为/Users/username,但是shell进程没有,因为它是一个不同的进程从改变目录的那个。

标签: c linux directory fork chdir


【解决方案1】:

正如您提到的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);
}

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 2013-12-18
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多