2

我正在尝试重新创建生产者/消费者问题。到目前为止,我得到的是使用 SystemV 创建共享内存和使用 POSIX 的信号量的主程序,以测试生产者进程是否可以访问它。到目前为止,这是我的代码:

有界缓冲区.c

#define SHMKEYPATH = "/dev/null" 
#define SHMKEYID 1
#define SEMKEYPATH = "/dev/null"
#define SEMKEYID 1

//Create Shared Memory
int shmid;
key_t shmkey;
void *shmaddress;
char *shm;

shmkey = ftok(SHMKEYPATH, SHMKEYID);
shmid = shmget(shmkey, sizeof(int) * 5, IPC_CREAT | S_IRUSR | S_IWUSR);
shmaddress = shmat(shmid, NULL, 0);
shm = (char*)(shmaddress);
*shm = 'b';
printf("Test share memory: currently %c",*shm);

//Create Semaphore
sem_t* my_semaphore;
char SEMAPHORE_NAME[] = "/my_semaphore5";
int my_semvalue = 10;
int value;

my_semaphore = sem_open(SEMAPHORE_NAME, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, my_semvalue);
sem_getvalue(my_semaphore, &value);
printf("sem val is %d\n", value);

//Execute Producer Process
int Ppid = fork();
if(Ppid == 0)
    execv("PATHTOPRODUCER", NULL);

//Print values from producer
shm = (char*)(shmaddress);
printf("%s", shm);

shmdt(shmaddress);
shmctl(shmid, IPC_RMID, NULL);

sem_getvalue(my_semaphore, &value);
printf("New val is %d", value);
sem_close(my_semaphore);
sem_unlink(SEMAPHORE_NAME);

生产者.c

//Test shared memory
void *shm_address;
int semid, shmid, rc;
key_t shmkey;

shkey = ftok(SHMKEYPATH, SHMKEYID);
shmid = shmget(shmkey, sizeof(int) *5, IPC_CREAT | S_IRUSR | S_IWUSR);
shm_address = shmat(shmid, NULL, 0);
char *shm;
shm = (char*)(shm_address);
shm = "testing";
shmdt(shm_address);

有两个问题。生产者正在更改共享内存,但是当我要求有界缓冲区告诉我内存是什么时,它和以前一样。这在某一时刻有效,但不再想工作。对于信号量,我不知道如何在不创建新信号量的情况下从生产者访问它们。

我一直在寻找很长时间,但我能找到的都是 POSIX 或两种 SystemV 解决方案,而不是 POSIX 用于信号量和 SystemV 用于共享内存(我必须使用它们,这是家庭作业)。

任何意见,将不胜感激。谢谢。

4

0 回答 0