面试题答案
一键面试#!/bin/bash
# 日志文件路径
LOG_FILE="md5_checksum.log"
# 函数定义,接收多个文件路径作为参数
calculate_md5() {
local files=("$@")
local num_files=${#files[@]}
local max_threads=10 # 定义最大线程数
local threads_running=0
local i=0
while [ $i -lt $num_files ]; do
# 检查正在运行的线程数是否小于最大线程数
while [ $threads_running -ge $max_threads ]; do
wait -n # 等待任意一个子进程结束
threads_running=$((threads_running - 1))
done
file_path="${files[$i]}"
md5sum "$file_path" >> $LOG_FILE & # 异步执行md5sum命令并将结果追加到日志文件
threads_running=$((threads_running + 1))
i=$((i + 1))
done
# 等待所有子进程完成
for ((j = 0; j < threads_running; j++)); do
wait
done
}
# 示例调用函数,传入多个文件路径
calculate_md5 file1.txt file2.txt /path/to/file3.txt
上述脚本定义了一个calculate_md5
函数,该函数接收多个文件路径作为参数,通过异步方式并行计算每个文件的MD5校验和,并将结果输出到md5_checksum.log
日志文件中。通过设置max_threads
变量来控制最大并行线程数,以平衡系统资源和执行效率。在实际使用中,可以根据系统的性能和文件数量调整max_threads
的值。