在生成子进程前,使用chdir()函数将当前目录更改为可执行文件目录。示例:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
char *exec_path = "/path/to/executable"; // 可执行文件路径
char *file_path = "/path/to/file"; // 文件路径
pid_t pid = fork();
if (pid == 0) { // 子进程
chdir(exec_path); // 更改当前目录为可执行文件目录
FILE *file = fopen(file_path, "r");
// 处理文件
fclose(file);
exit(0);
} else if (pid > 0) { // 父进程
int status;
waitpid(pid, &status, 0);
} else { // fork()失败
perror("fork");
exit(1);
}
return 0;
}