html

设计一个程序,作为进程A,进程A专门创建一个信号量集,要求信号量集中有1个信号量,对信号量集合中的信号量进行设置,要求集合中的信号量的初值为1,然后再设计2个程序,分别是进程B和进程C,要求进程B和进程C使用进程A创建的信号量集合中的信号量

设计一个程序,作为进程A,进程A专门创建一个信号量集,要求信号量集中有1个信号量,对信号量集合中的信号量进行设置,要求集合中的信号量的初值为1,然后再设计2个程序,分别是进程B和进程C,要求进程B和进程C使用进程A创建的信号量集合中的信号量实现互斥访问。 提示:进程A、进程B、进程C需要使用共享内存作为临界资源的访问。

//进程A (create_shared_memory_and_semaphore.c)
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <fcntl.h>  
#include <sys/ipc.h>  
#include <sys/shm.h>  
#include <sys/sem.h>  
#include <sys/types.h>  
#include <unistd.h>  
  
#define SHM_SIZE 1024  
#define SEM_NAME "/my_semaphore"  
  
int main() {  
    key_t key = ftok("/tmp", 'R'); // 用于创建共享内存和信号量的唯一键  
  
    // 创建共享内存  
    int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);  
    if (shmid == -1) {  
        perror("shmget");  
        exit(1);  
    }  
  
    // 附加到共享内存  
    char *shm_ptr = (char *)shmat(shmid, NULL, 0);  
    if (shm_ptr == (char *)-1) {  
        perror("shmat");  
        exit(1);  
    }  
  
    // 写入一些数据到共享内存(可选)  
    strcpy(shm_ptr, "Hello from Process A!");  
  
    // 创建信号量集  
    int semid = semget(key, 1, IPC_CREAT | 0666);  
    if (semid == -1) {  
        perror("semget");  
        exit(1);  
    }  
  
    // 初始化信号量(初值为1)  
    union semun semopts;  
    semopts.val = 1;  
    if (semctl(semid, 0, SETVAL, semopts) == -1) {  
        perror("semctl");  
        exit(1);  
    }  
  
    // 假设我们将semid存储在文件中以便其他进程可以读取  
    FILE *fp = fopen(SEM_NAME, "w");  
    if (fp == NULL) {  
        perror("fopen");  
        exit(1);  
    }  
    fprintf(fp, "%d", semid);  
    fclose(fp);  
  
    // 分离共享内存(进程A不再需要访问共享内存,但为了演示目的我们保留它附加)  
    // shmdt(shm_ptr); // 注释掉,因为进程A还要保持运行以观察其他进程  
  
    // 等待其他进程完成(这里简单使用sleep模拟)  
    sleep(100); // 等待足够长的时间以便其他进程可以运行  
  
    // 清理(在真实场景中,你可能希望更优雅地处理清理)  
    // shmdt(shm_ptr);  
    // shmctl(shmid, IPC_RMID, NULL);  
    // semctl(semid, 0, IPC_RMID, NULL);  
  
    return 0;  
}
//进程B和进程C (access_shared_memory.c)
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <fcntl.h>  
#include <sys/ipc.h>  
#include <sys/shm.h>  
#include <sys/sem.h>  
#include <sys/types.h>  
#include <unistd.h>  
  
#define SHM_SIZE 1024  
#define SEM_NAME "/my_semaphore"  
  
int main() {  
    key_t key = ftok("/tmp", 'R'); // 与进程A相同的键  
  
    // 从文件中读取semid  
    FILE *fp = fopen(SEM_NAME, "r");  
    if (fp == NULL) {  
        perror("fopen");  
        exit(1);  
    }  
    int semid;  
    fscanf(fp, "%d", &semid);  
    fclose(fp);  
  
    // 获取共享内存  
    int shmid = shmget(key, SHM_SIZE, 0); //
posted @ 2024-06-11 13:41  大螺丝贼六  阅读(29)  评论(0)    收藏  举报
html