作业1: 1:使用write 和 read 实现 文件夹拷贝功能,不考虑递归拷贝
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#define BUFFER_SIZE 1024
void copy_file(const char *src, const char *dest) {
int src_fd = open(src, O_RDONLY);
if (src_fd == -1) {
perror("打开源文件失败");
exit(1);
}
int dest_fd = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd == -1) {
perror("打开目标文件失败");
exit(1);
}
char buffer[BUFFER_SIZE];
ssize_t bytes_read;
while ((bytes_read = read(src_fd, buffer, BUFFER_SIZE)) > 0) {
if (write(dest_fd, buffer, bytes_read) != bytes_read) {
perror("write");
exit(1);
}
}
if (bytes_read == -1) {
perror("read");
exit(1);
}
close(src_fd);
close(dest_fd);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_dir> <destination_dir>\n", argv[0]);
exit(1);
}
DIR *dir = opendir(argv[1]);
if (!dir) {
perror("opendir");
exit(1);
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) {
char src_path[256];
char dest_path[256];
snprintf(src_path, sizeof(src_path), "%s/%s", argv[1], entry->d_name);
snprintf(dest_path, sizeof(dest_path), "%s/%s", argv[2], entry->d_name);
copy_file(src_path, dest_path);
}
}
closedir(dir);
return 0;
}
作业2: 使用循环+fork的形式。创建一条进程链,链条上总共有100个进程 要求:程序不崩溃
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
for (int i = 0; i < 100; i++) {
int res = fork();
if (res < 0) {
perror("fork failed");
return 1;
} else if (res == 0) {
printf("第 %d层的子进程PID是 %d, 它的父进程PID是 %d\n", i+1, getpid(), getppid());
} else {
wait(NULL);
break;
}
}
return 0;
}