c - 使用 chdir 更改当前工作目录
问题描述
我正在创建一个类似于“shell解释器”的程序,但在C中,如果我在命令行“更改名称”中编写名为“Bash”的主程序,它会创建一个fork并执行一个execlp来调用程序“cd " 谁应该改变我的当前目录
if(strcmp(argv[0], "change"){
pid = fork();
if (pid == 0){
execlp("./cd", "./cd", argv[1], NULL);
}
它运行良好,它运行我的程序 cd 并且理论上会发生变化,但是在程序结束后它会返回到 Elder 目录
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
//PWD
int main(int argc, char *argv[]) {
char diratual[90], dir[90], barra[90] = "/";
char *local[argc];
local[0] = argv[1];
getcwd(diratual, sizeof(diratual));
strncat(diratual, barra, sizeof(barra));
strncat(diratual,local[0],sizeof(local[0]));
chdir(diratual);
system("pwd");
}
我使用字符串来创建完整的路径目标,我在整个执行后测试程序,它会返回我输入的路径,但是当我在主程序中键入“pwd”时它会显示较旧的路径。例子:
我在 /home/user/Documents
并想进入 /home/user/Documents/Test
所以我输入“更改测试”
它接收 'Test' 作为 arg[1] 并与程序内部字符串对齐以创建一个名为:
string = "/home/user/Documents/Test"
之后我使用 - chdir(string);
所以最后 system("pwd"); 返回预期的“/home/user/Documents/Test”
但是当程序结束时它返回到主程序
当我在我的主程序中输入 pwd 时,它会显示 '/home/user/Documents
我该如何解决这个问题?进入并停留在键入的目录中?
解决方案
推荐阅读
- python - 当远程进程完成时,Python 会中断 tail -f 进程
- node.js - 环境中的 RSA 密钥导致错误
- java - 两个决策变量的 Java Cplex 乘积
- docker - 删除较旧的 docker 映像,但不删除仍被引用的层
- message-queue - 选举分布式系统的新领导者
- android - PackageManager.checkPermission 有时会提供不正确的结果
- c++-winrt - 是否可以使用 C++/winrt 来构建 COM 对象而不是例如使用 ATL?
- vba - 使用 ctrl+shift+down 函数 aka Selection.End(x1down) 进行动态复制和粘贴
- antlr4 - Antlr4 语法不会解析多行输入
- django - Django - 未找到“list1”的反向。“list1”不是有效的视图函数或模式名称