c++ - 如何使用 chdir 更改目录?
问题描述
我目前正在创建自己的 linux shell。我可以在我的目录中“ls”等等。但是,当我尝试“cd”进入子目录时,它实际上从未改变。代码运行但实际上并没有更改我的目录。在我的 linux 文件系统上,我有目录
/
home
testing
foo.txt
testingForShell
bar.txt
要获取当前目录,我正在使用...
void execute(string command, char *
const * args, char * path) {
int pid = -5;
int child = -5;
int status;
pid = fork();
if (pid == 0) {
if (command.substr(command.length() - 2).compare("cd") == 0) {
const char * currentPath;
if ((currentPath = getenv("HOME")) == NULL) {
currentPath = getpwuid(getuid()) -> pw_dir;
}
cout << (string(currentPath) + "/" + string(args[1])).c_str() << endl;
int dir = chdir((string(currentPath) + "/" + string(args[1])).c_str());
} else {
char * pathArgs = strtok(path, ":");
while (pathArgs != NULL) {
try {
execv((string(pathArgs) + "/" + command).c_str(), args);
} catch (...) {
}
pathArgs = strtok(NULL, ":");
}
}
exit(0);
} else {
waitpid(-1, & status, 0);
}
}
子进程中的第一个 if 是他们是否要“cd”到一个目录中。else 用于其他命令,例如“ls”。cout 打印出来,/home/testing/testingForShell
但是当我再次调用“ls”时,它从未进入目录以显示 bar.txt。如果我提供了足够的信息,请告诉我。我非常有信心我使用 chdir 错误,但情况可能并非如此。注意:我正在尝试更改正在运行的脚本中的目录,而不是我启动脚本的实际 linux 终端。
解决方案
在分叉进程中更改工作目录将正常工作......在该分叉进程中。
但它对父母没有任何作用。因此,执行的下一个命令与之前位于同一工作目录中。
推荐阅读
- ios - 为属性字符串属性赋值后布局 UILabel
- ruby-on-rails - 将 React 用作前端时,如何在我的 Ruby API 中访问用户的 Google 日历?
- android - CollapsingToolbarLayout 中的工具栏没有从 AppTheme 继承 fontFamily
- reactjs - 更改所有子元素的字体大小和颜色
- sql - 使用 Airflow 将 Bigquery 查询结果发送到数据框
- database - PHP脚本将数据库从一台服务器复制到另一台服务器
- c# - 新的 Texture2D 和 Texture.SetData 将在大多数情况下工作,但它会导致事情挂起
- node.js - 如何发送遍历来自firestore数据库的数组的电子邮件
- python - 通过对烧瓶的 ajax 调用从另一个驱动器更改图像源
- sql - SQL:如何返回前 4、13 和 52 周的计数?