是否可以使用 fork 命令更改目录?在不深入研究我的代码的情况下,我有以下内容:
childpid = fork();
if (childpid >= 0)
{
if (childpid == 0)
{
ret = execvp(argv[0],argv);
exit(ret);
} else {
waitpid(childpid,&status,0);
ret = WEXITSTATUS(status);
}
}
当我输入诸如 ls
、pwd
等基本命令时,上面的代码工作正常。是否可以实现一种使用 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/