#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<wait.h>
#include<sys/shm.h>/*共享内存*/
#include<sys/sem.h>/*信号量*/
#include<string.h>
#define MAX_SIZE 100
#define SHM_KEY_T 9494/*共享内存键*/
#define SEM_KEY_T 8989/*信号量键*/
struct SHM_BLOCK
{
int semid;
int datacount;
int beginpos;
int curpos;
char data[MAX_SIZE];
};
void child_process();
void parent_process();
struct SHM_BLOCK *block;
struct sembuf buf;
int pid;
int shmid;
int main(void)
{
shmid = shmget(SHM_KEY_T, sizeof(struct SHM_BLOCK), 0666 | IPC_CREAT);
block = (struct SHM_BLOCK*)shmat(shmid, (const void*)0, 0);
block->semid = semget(SEM_KEY_T, 1, 0666 | IPC_CREAT);
block->datacount = 0;
block->beginpos = 0;
block->curpos = 0;
semctl(block->semid, 0, SETVAL, 1);
pid = fork();
if(pid == 0)
child_process();
else
parent_process();
return 0;
}
void child_process()
{
printf("Im child Process pid is %d lets begin do work\n", getpid());
int taskcount = 0;
char task;
buf.sem_flg = 0;
buf.sem_num = 0;
while(taskcount < 200)
{
buf.sem_op = -1;
semop(block->semid, &buf, 1);
buf.sem_op = 1;
if(block->datacount == 0)
{
semop(block->semid, &buf, 1);
continue;
}
block->datacount--;
task = block->data[block->beginpos++];
block->beginpos %= MAX_SIZE;
semop(block->semid, &buf, 1);
taskcount++;
printf("cur task is %d the data is %c\n", taskcount, task);
}
shmdt((const void*)block);
return;
}
void parent_process(void)
{
printf("Im parent Process pid is %d lets begin add work\n", getpid());
buf.sem_flg = 0;
buf.sem_num = 0;
int taskcount = 0;
while(taskcount < 200)
{
buf.sem_op = -1;
semop(block->semid, &buf, 1);
buf.sem_op = 1;
if(block->datacount >= MAX_SIZE)
{
semop(block->semid, &buf, 1);
continue;
}
block->datacount++;
block->data[block->curpos++] = 'a' + taskcount%26;
block->curpos %= MAX_SIZE;
semop(block->semid, &buf, 1);
taskcount++;
}
waitpid(pid, NULL, 0);
semctl(block->semid, 0, IPC_RMID);
shmdt((const void*)block);
shmctl(shmid, IPC_RMID, 0);
return;
}