|
发表于 2023-10-8 10:24:48
|
显示全部楼层
chdir() 函数用于改变当前工作目录。根据你提供的代码,如果 chdir() 函数返回值不为 0,即表示切换目录失败。在这种情况下,你使用 perror("chdir") 打印了一个错误消息,但这并不会导致程序退出或终止。
根据你的描述,你输入了 "cd /mnt" 命令,但是当前工作目录并没有改变。这可能是因为你的代码是在子进程中执行的,而子进程的工作目录的改变不会影响到父进程的工作目录。
解决这个问题的方法是使用 chdir() 函数来改变父进程的工作目录。你可以在父进程中执行 chdir() 函数,然后在子进程中执行其他的命令。
以下是一个示例代码:
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- int main() {
- char command[] = "cd /mnt";
-
- pid_t pid = fork();
-
- if (pid == 0) {
- // 子进程
- system(command);
- exit(0);
- } else if (pid > 0) {
- // 父进程
- wait(NULL);
- chdir("/mnt");
- printf("当前工作目录:%s\n", getcwd(NULL, 0));
- } else {
- // fork() 失败
- perror("fork");
- return 1;
- }
-
- return 0;
- }
复制代码
在这个示例代码中,我们使用 fork() 函数创建了一个子进程。子进程通过 system() 函数执行了 "cd /mnt" 命令。父进程在子进程执行完毕后,使用 chdir() 函数切换到 /mnt 目录,并打印当前工作目录。
希望这个解答能够帮到你!如果你有任何疑问,请随时追问。 |
|