使用linux c编写一个demo,能够生成1000个随机大小为1K到50M的so文件,并调用这些so
下面是一个完整的 Linux C 程序示例,它能够生成 1000 个随机大小(1K 到 50M)的共享库文件(.so 文件),并调用这些共享库中的函数。
1. 生成共享库的代码
generate_so.c
这个程序用于生成 1000 个共享库文件,每个共享库包含一个简单的函数。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
// 生成随机大小的文件
void generate_random_file(const char *filename, size_t size) {
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
char *buffer = malloc(size);
if (!buffer) {
perror("malloc");
close(fd);
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < size; i++) {
buffer[i] = rand() % 256;
}
if (write(fd, buffer, size) != size) {
perror("write");
free(buffer);
close(fd);
exit(EXIT_FAILURE);
}
free(buffer);
close(fd);
}
// 生成共享库文件
void generate_shared_library(const char *filename) {
char command[512];
snprintf(command, sizeof(command),
"gcc -shared -fPIC -o %s -x c - <<EOF\n"
"#include <stdio.h>\n"
"void hello() {\n"
" printf(\"Hello from %s!\\n\");\n"
"}\n"
"EOF",
filename, filename);
system(command);
}
int main() {
srand(time(NULL));
for (int i = 0; i < 1000; i++) {
char so_filename[256];
snprintf(so_filename, sizeof(so_filename), "lib%d.so", i);
// 生成随机大小(1K - 50M)
size_t size = (rand() % (50 * 1024 * 1024 - 1
