不知道消费者为什么做所有的工作?带信号和叉的产品消费者
我为产品为10个整数的数组创建了一个semaphor,该数组填充了名称,并且返回1和0(二进制)。即使生产者正在释放信号,也会调用消费者。
为什么会发生这种情况?
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
#define SIZE 10
#define KEY 1234
int *Memory;
int i, j;
sem_t *sem;
char *name = "Hello";
int main(int argc, const char *argv[])
{
int shmid;
if ((shmid = shmget(KEY, sizeof(int) * SIZE, IPC_CREAT | S_IRWXU)) < 0)
{
perror("Error while creating shmget");
return 1;
}
pid_t pid;
sem = sem_open(name, O_CREAT, S_IRUSR | S_IWUSR, 1);
if ((pid = fork()) != 0)
{
if ((shmid = shmget(KEY, sizeof(int) * SIZE, S_IRWXU)) < 0)
{
perror("error in shmget");
return 1;
}
Memory = (int *)shmat(shmid, NULL, 0);
if (Memory == NULL)
{
perror("error in shmat");
return 1;
}
for (i = 0; i < 10; i++)
{
sem_wait(sem);
Memory[j] = i;
printf("Produced %i in box %i\n", i + 1, i + 1);
sem_post(sem);
sleep(1);
}
int status;
wait(&status);
sem_unlink(name);
sem_destroy(sem);
struct shmid_ds shmid_ds1;
if (shmctl(shmid, IPC_RMID, &shmid_ds1) < 0)
{
perror(
"Error in the father while executing shmctl when it was "
"elimnating the segment of shared memory");
}
}
else
{
if ((shmid = shmget(KEY, sizeof(int) * SIZE, S_IRWXU)) < 0)
{
perror("error in the producer with the shmget");
return 1;
}
Memory = (int *)shmat(shmid, NULL, 0);
if (Memory == NULL)
{
perror("error in the producer with the shmat");
return 1;
}
for (i = 0; i < 10; i++)
{
sem_wait(sem);
Memory[i] = -1;
printf("Consume and now it is %i in box %i\n", Memory[i], i + 1);
sem_post(sem);
}
}
return 0;
}
,输出是:
Produced 1 in box 1
Consume and now it is -1 in box 1
Consume and now it is -1 in box 2
Consume and now it is -1 in box 3
Consume and now it is -1 in box 4
Consume and now it is -1 in box 5
Consume and now it is -1 in box 6
Consume and now it is -1 in box 7
Consume and now it is -1 in box 8
Consume and now it is -1 in box 9
Consume and now it is -1 in box 10
Produced 2 in box 2
Produced 3 in box 3
Produced 4 in box 4
Produced 5 in box 5
Produced 6 in box 6
Produced 7 in box 7
Produced 8 in box 8
Produced 9 in box 9
Produced 10 in box 10
谢谢@ user2485710我已经使用线程来解决问题,并且完美地工作。但是你知道我怎么能用信号量和叉子来解决消费者生产? – user3606231
@ user3606231右侧的名称是发布帖子的用户的名称,我刚刚编辑它以修复缩进。 – user2485710