diff --git a/execve_intercept.c b/execve_intercept.c index a9a4918..44f9ae8 100644 --- a/execve_intercept.c +++ b/execve_intercept.c @@ -114,75 +114,25 @@ void write_log(const char *filename, char *const argv[]) { // 复制标准输出和错误输出到日志文件 void duplicate_output_to_log() { - int stdout_pipe[2], stderr_pipe[2]; - - // 创建 stdout 和 stderr 的管道 - if (pipe(stdout_pipe) < 0 || pipe(stderr_pipe) < 0) { - perror("pipe"); + int out_fd = open(LOG_OUT_FILE, O_WRONLY | O_CREAT | O_APPEND, 0644); + if (out_fd == -1) { + perror("Failed to open log file"); return; } - pid_t pid = fork(); - if (pid < 0) { - perror("fork"); + // 复制 stdout 和 stderr 到 log 文件 + if (dup2(out_fd, STDOUT_FILENO) == -1 || dup2(out_fd, STDERR_FILENO) == -1) { + perror("Failed to redirect output"); + close(out_fd); return; } - if (pid == 0) { // 子进程 - close(stdout_pipe[1]); // 关闭 stdout 写端 - close(stderr_pipe[1]); // 关闭 stderr 写端 - - // 打开日志文件(追加模式) - int log_fd = open(LOG_OUT_FILE, O_WRONLY | O_CREAT | O_APPEND, 0644); - if (log_fd < 0) { - perror("open log file"); - exit(1); - } - - // 让 tee 进程读取 stdout_pipe[0] 并写入日志和终端 - dup2(stdout_pipe[0], STDIN_FILENO); - dup2(log_fd, STDOUT_FILENO); - execlp("tee", "tee", "/dev/tty", NULL); - perror("execlp tee stdout"); - exit(1); - } - - pid_t pid_err = fork(); - if (pid_err < 0) { - perror("fork"); - return; - } - - if (pid_err == 0) { // 另一个子进程 - close(stderr_pipe[1]); // 关闭 stderr 写端 - - int log_fd = open(LOG_OUT_FILE, O_WRONLY | O_CREAT | O_APPEND, 0644); - if (log_fd < 0) { - perror("open log file"); - exit(1); - } - - // 让 tee 进程读取 stderr_pipe[0] 并写入日志和终端 - dup2(stderr_pipe[0], STDIN_FILENO); - dup2(log_fd, STDOUT_FILENO); - execlp("tee", "tee", "/dev/tty", NULL); - perror("execlp tee stderr"); - exit(1); - } - - // 父进程 - close(stdout_pipe[0]); // 关闭 stdout 读端 - close(stderr_pipe[0]); // 关闭 stderr 读端 - - // 让标准输出、错误输出流向管道 - dup2(stdout_pipe[1], STDOUT_FILENO); - dup2(stderr_pipe[1], STDERR_FILENO); - - close(stdout_pipe[1]); // 关闭写端(子进程 tee 负责处理) - close(stderr_pipe[1]); + // 关闭文件描述符,因为 stdout/stderr 现在已经指向它 + close(out_fd); } + typedef int (*orig_execve_type)(const char *filename, char *const argv[], char *const envp[]); diff --git a/intercept.so b/intercept.so index e05f950..49bbfac 100755 Binary files a/intercept.so and b/intercept.so differ