实验一
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
int main() {
// 文件读写示例
FILE *file = fopen("example.txt", "w");
if (file) {
fprintf(file, "Hello, World!\n");
fclose(file);
printf("File written successfully.\n");
} else {
perror("Error opening file for writing");
return 1;
}
// 读取刚才写入的文件
file = fopen("example.txt", "r");
if (file) {
char buffer[1024];
size_t len;
while ((len = fread(buffer, sizeof(char), sizeof(buffer) - 1, file)) > 0) {
buffer[len] = '\0'; // 确保字符串正确以 null 结尾
printf("%s", buffer);
}
fclose(file);
} else {
perror("Error opening file for reading");
return 1;
}
// 列出当前目录内容
DIR *dir = opendir(".");
if (dir) {
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
} else {
perror("Error opening directory");
return 1;
}
// 创建新目录
mode_t mode = 0777; // 设置权限
if (mkdir("new_directory", mode) == -1) {
perror("Error creating directory");
return 1;
}
printf("Directory created successfully.\n");
return 0;
}
实验二
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <string.h>
#define SHM_SIZE 1024
#define SEM_NAME "/mysem"
int main() {
key_t key = ftok("/tmp", 'R');
int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
char *shm_ptr = shmat(shmid, NULL, 0);
int semid = semget(ftok(SEM_NAME, 0), 1, IPC_CREAT | 0666);
union semun sem_union = {1};
semctl(semid, 0, SETVAL, sem_union);
pid_t pid = fork();
if (pid < 0) exit(1);
if (pid == 0) { // 子进程
struct sembuf sem_b = {0, -1, 0};
semop(semid, &sem_b, 1);
strcpy(shm_ptr, "Hello from child!");
sem_b.sem_op = 1;
semop(semid, &sem_b, 1);
} else { // 父进程
sleep(1);
struct sembuf sem_b = {0, -1, 0};
semop(semid, &sem_b, 1);
printf("Data from shared memory: %s\n", shm_ptr);
sem_b.sem_op = 1;
semop(semid, &sem_b, 1);
}
return 0;
}
实验三
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#define SHM_SIZE 1024
int main() {
key_t key;
int shmid;
char *shm_ptr;
pid_t pid;
// 创建唯一的 key 值
key = ftok("/tmp", 'R');
// 创建共享内存段
shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
// 附加共享内存到进程的地址空间
shm_ptr = shmat(shmid, NULL, 0);
if (shm_ptr == (char *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
// 清除共享内存中的任何旧数据
memset(shm_ptr, 0, SHM_SIZE);
// 创建子进程
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
// 等待父进程写入数据(这里简单使用 sleep 模拟)
sleep(1);
// 读取共享内存中的数据
printf("Child received: %s\n", shm_ptr);
// 分离共享内存段
shmdt(shm_ptr);
exit(EXIT_SUCCESS);
} else { // 父进程
// 向共享内存中写入数据
strcpy(shm_ptr, "Hello from parent");
// 等待子进程读取数据(这里简单使用 sleep 模拟)
sleep(2);
// 分离共享内存段(父进程也可以这么做,但通常在最后一个使用它的进程中执行)
shmdt(shm_ptr);
// 清理共享内存(可选,通常在不再需要时由某个进程执行)
// shmctl(shmid, IPC_RMID, NULL);
}
// 父进程继续执行其他任务或退出
return 0;
}