首页 > 解决方案 > 使用 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

我该如何解决这个问题?进入并停留在键入的目录中?

标签: clinuxlinux-kernel

解决方案


推荐阅读