进一步研究我的代码。在用户的帮助下,我设法在代码中实现了共享内存。但是我遇到了一个问题。此代码仅用于演示缓冲区输入和输出算法。
In wait_t()
the while loop keeps going even when sem_wait()
is called. The loop should stop when the wait is called when length is under 1. I've tried using break;
to stop the loop and when is called sem_post()
the length was still 3 instead of 0.
So how can I get the while loop to stop when sem_wait()
is called and how to share length across both functions since it uses processes.
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/ipc.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
sem_t *mutex;
int length;
int out;
int in;
void wait_t(int a)
{
while(1){
if (a < 1)
{
sem_wait(&mutex);
printf("waiting\n");
//doesn't stop unless break;
}
//write to buffer
a--;
printf("a\n");
}
}
void signal_t(int a)
{
printf("length = %d \n", a);
while(a != 3){
if (a < 1)
{
sem_post(&mutex);
printf("signal\n");
}
//print to buffer
printf("b\n");
a++;
}
}
int main()
{
length = 3;
int shared_mem_id = shmget(IPC_PRIVATE, sizeof(sem_t), IPC_CREAT);
mutex = shmat(shared_mem_id, NULL, 0);
sem_init(&mutex, 1, 1);
int i = -2;
if(fork() == 0){ // create 1st child process
mutex = shmat(shared_mem_id, NULL, 0);
wait_t(length);
exit(0);
}
shmdt(mutex);
wait(NULL);
if(fork() == 0){ // create 2nd child process
mutex = shmat(shared_mem_id, NULL, 0);
signal_t(length);
exit(0);
}
shmdt(mutex);
wait(NULL);
if(fork() == 0){ // create 3nd child process
mutex = shmat(shared_mem_id, NULL, 0);
signal_t(i);
exit(0);
}
shmdt(mutex);
wait(NULL);
printf("%d\n", i);
exit(0);
}