C语言子进程切换工作目录问题求助:scanf无响应、目录未变更
问题分析与修复方案
咱们一步步拆解并修复你遇到的两个问题:
1. scanf无响应的原因
当父进程调用exit(1)直接退出后,子进程会变成孤儿进程,被系统的init(或systemd)进程收养。这时候子进程的标准输入(stdin)会和原终端断开连接,导致scanf无法等待用户输入,程序直接跳过输入步骤结束。
解决办法很简单:让父进程等待子进程执行完毕后再退出,保证子进程始终和终端保持连接。
2. 无法切换目录的原因
你的代码里有两个细节错误导致chdir失效:
scanf("%s", &newdirectory);参数错误:newdirectory本身就是数组的首地址,不需要加&,加&后传递的是数组指针的地址,类型不匹配,会导致输入内容写入错误的内存区域。- 你测试的路径
home/usr/desktop是相对路径,它是相对于当前工作目录的路径,但通常用户桌面的绝对路径是/home/你的用户名/Desktop(注意首字母大写和开头的/),如果路径格式错误或目标路径不存在,chdir会失败,但你没有检查它的返回值,所以无法发现问题。
修改后的完整代码
#include <unistd.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/wait.h> // 新增头文件,用于wait函数 int main() { int pid; char directory[1024]; char newdirectory[1024]; pid = fork(); if (pid < 0) { perror("\nFork failed"); // 用perror更清晰地打印错误原因 exit(EXIT_FAILURE); } else if (pid == 0) { printf("I'm child \n"); printf(" My PID: %d \n", getpid()); // 获取当前目录并检查是否成功 if (getcwd(directory, sizeof(directory)) == NULL) { perror("getcwd failed"); exit(EXIT_FAILURE); } printf(" My current working directory is: %s\n", directory); printf(" Enter the new path: "); // 修正scanf参数,去掉多余的& if (scanf("%s", newdirectory) != 1) { fprintf(stderr, "Failed to read input\n"); exit(EXIT_FAILURE); } // 切换目录并检查返回值,失败时打印错误 if (chdir(newdirectory) == -1) { perror("chdir failed"); // 会提示具体错误,比如路径不存在、权限不足等 exit(EXIT_FAILURE); } // 再次获取目录确认切换结果 if (getcwd(directory, sizeof(directory)) == NULL) { perror("getcwd failed"); exit(EXIT_FAILURE); } printf(" Path changed to: %s\n", directory); exit(EXIT_SUCCESS); } else { printf("I'm a parent \n"); printf("My PID is %d \n", getpid()); printf("Waiting for child to finish...\n"); // 父进程等待子进程完成,避免子进程变成孤儿导致输入异常 wait(NULL); printf("Bye bye \n"); exit(EXIT_SUCCESS); } return 0; }
关键修改点说明
- 新增
#include <sys/wait.h>,用wait(NULL)让父进程等待子进程执行完毕后再退出,确保子进程能正常读取终端输入。 - 修正
scanf的参数为newdirectory,去掉多余的&,保证输入内容正确写入数组。 - 为
getcwd、scanf、chdir添加返回值检查,用perror打印具体错误信息,方便调试排查问题。 - 把
exit(1)/exit(0)替换为标准的EXIT_FAILURE/EXIT_SUCCESS,代码更规范易读。
测试时输入绝对路径(比如/home/你的用户名/Desktop,根据你的实际系统路径调整),就能成功切换目录啦。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

