Question: In C / C + + The project will require learning three Unix techniques: forking a child, using POSIX semaphores, using POSIX shared memory. The

In C/C++ The project will require learning three Unix techniques: forking a child, using POSIX semaphores, using POSIX shared memory. The program should create named semaphores which both parent and child can access. It should then create a block of shared memory that will serve as a shared buffer. The producer should begin placing numbers 1 to 100 into the shared buffer while the consumer begins getting the numbers out of the buffer and printing them. The actions should be coordinated using semaphores, as shown in slides 34 and 35 of the chapter 6 slides. The buffer should hold 5 numbers. Examples of the three needed techniques will be in eLearning.
SLIDES 34 & 35
do {
.../* produce an item in next_produced */
...
wait(empty);
wait(mutex);
.../* add next produced to the buffer */
...
signal(mutex);
signal(full);
} while (true);
Do {
wait(full);
wait(mutex);
.../* remove an item from buffer to next_consumed */
...
signal(mutex);
signal(empty);
.../* consume the item in next consumed */
...} while (true);
ADDITIONAL CODE ALSO NEEDED:
int main()
{
pid_t pid;
const char *semname ="/delay";
sem_t *semaphore = sem_open(semname, O_CREAT | O_EXCL, 0600,0);
if (semaphore == SEM_FAILED)
{
printf("Create semaphore
");
exit(1);
}
switch (pid = fork())
{
case -1:
cout << "The fork failed!";
exit(-1);
case 0:
if (sem_wait (semaphore)==-1)
{
printf("Wait on semaphore
");
exit(1);
}
cout << "Child: hello!
";
_exit(0);
default:
cout << "Parent running...
";
if (sem_post (semaphore)==-1)
{
printf("Post semaphore
");
exit(1);
}
waitpid(-1, NULL, 0);
if (sem_close(semaphore)==-1)
{
printf("Close semaphore
");
exit(1);
}
if (sem_unlink(semname)==-1)
{
printf("Unlink semaphore
");
exit(1);
}
}
}
int main()
{
pid_t pid;
const char *shmname ="/myshare";
int sharefd = shm_open(shmname, O_CREAT | O_RDWR,0600);
if (sharefd ==-1)
{
printf("Create shared memory failed
");
exit(1);
}
int trunc = ftruncate(sharefd, sizeof(int));
if (trunc ==-1)
{
printf("Truncate failed
");
exit(1);
}
void *ptr = mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, sharefd, 0);
if (ptr == MAP_FAILED)
{
printf("mmap failed
");
exit(1);
}
int *iptr =(int*)ptr;
switch (pid = fork())
{
case -1:
cout << "The fork failed!";
exit(-1);
case 0:
{
sleep(2); // use semaphore instead
int x =*iptr;
cout << "Child read "<< x << endl;
}
_exit(0);
default:
{
int y =5;
*iptr = y;
}
waitpid(-1, NULL, 0);
if (shm_unlink(shmname)==-1)
{
printf("Unlink shm
");
exit(1);
}
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!