我正在尝试重新创建生产者/消费者问题。到目前为止,我所使用的是使用SystemV创建共享内存的主程序和使用POSIX的信号量,以测试生产者进程是否可以访问它。 到目前为止,这是我的代码:
boundedbuffer.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);
producer.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用于共享内存(我必须使用它们,这是作业)。
任何建议都将不胜感激。 感谢。