Linux Programming and Data Mining Lab, Exams of Linux skills

C Programming and Linux Linux Programming and Data Mining Lab Operating Systems

Typology: Exams

2019/2020

Uploaded on 05/13/2020

ibadatmammadov
ibadatmammadov 🇦🇿

1 document

1 / 3

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
English version Translate version
For each exercise
Intermediary versions of the running program, with
running code + execution trace output + explanation
of each step
Complete version of the running program, with
running code + execution trace output + explanation
of each step
1. Exercise 1
Write a program containing two processes:
1.1. The first process initializes a shared memory
segment and a group of two semaphores. It creates the
son process, then reads all data in the segment and prints
them.
1.2. The son process computes the data using a compute
function that returns 0 when all data are computed. It
transmits them to the father through the shared memory
segment.
To write a data, the son makes a P on the first
semaphore, writes the data, and makes a V on thesecond
semaphore. Symmetrically, the father makes a P on the
second semaphore, reads the data and makes a V on the
first semaphore.
2. Exercise 2.
Based on previous exercise, write two programs.
2.1. The first program is called as follows:
producer n
where n is an integer. The value is set in the shared
memory segment after the last value already available.
If no space is available any more, the program waits for
space to be freed by the second program.
2.2. The second program, consumer, does NOT take
any argument and returns the first value saved
in the shared memory segment. If no value is
available, the program will wait for the producer
to store a value.
Please note that all consumers must share the index of
the first saved value. Similarly, all producers must share
the index of the first free space. The shared memory
segment thus contains both indices. They are critical
variables that need to be protected through mutual
exclusion semaphores.
.
За каждое упражнение
Промежуточные версии работающей
программы, с запущенным кодом + вывод
трассы выполнения + объяснение каждого
шага
Полная версия работающей программы, с
запущенным кодом + вывод трассы
выполнения + объяснение каждого шага
1. Упражнение 1
Напишите программу, содержащую два
процесса:
1.1. Первый процесс инициализирует сегмент
общей памяти и группу из двух семафоров. Он
создает процесс сына, затем читает все данные
в сегменте и печатает их.
1.2. Процесс son вычисляет данные, используя
функцию вычисления, которая возвращает 0,
когда вычисляются все данные. Он передает их
отцу через сегмент общей памяти.
Чтобы записать данные, сын делает P на
первом семафоре, записывает данные и делает
V на втором семафоре. Симметрично отец
делает P на втором семафоре, читает данные и
делает V на первом семафоре.
2. Упражнение 2.
Основываясь на предыдущем упражнении,
напишите две программы.
2.1. Первая программа называется следующим
образом:
producer n
где n - целое число Значение устанавливается в
сегменте совместно используемой памяти
после последнего доступного значения. Если
свободного места больше нет, программа
ожидает освобождения места второй
программой.
2.2. Вторая программа, consumer, NOT
принимает никаких аргументов и возвращает
первое значение, сохраненное в сегменте
разделяемой памяти. Если значение
недоступно, программа будет ждать, пока
производитель сохранит значение.
Обратите внимание, что все потребители
должны использовать индекс первого
сохраненного значения. Точно так же все
производители должны делиться индексом
первого свободного места. Таким образом,
сегмент общей памяти содержит оба индекса.
Они являются критическими переменными,
которые необходимо защищать с помощью
семафоров взаимного исключения.
pf3

Partial preview of the text

Download Linux Programming and Data Mining Lab and more Exams Linux skills in PDF only on Docsity!

English version Translate version

For each exercise

Intermediary versions of the running program, with running code + execution trace output + explanation of each stepComplete version of the running program, with running code + execution trace output + explanation of each step

1. Exercise 1 Write a program containing two processes: 1.1. The first process initializes a shared memory segment and a group of two semaphores. It creates the son process, then reads all data in the segment and prints them. 1.2. The son process computes the data using a compute function that returns 0 when all data are computed. It transmits them to the father through the shared memory segment.

To write a data, the son makes a P on the first semaphore, writes the data, and makes a V on thesecond semaphore. Symmetrically, the father makes a P on the second semaphore, reads the data and makes a V on the first semaphore.

2. Exercise 2. Based on previous exercise, write two programs. 2.1. The first program is called as follows: producer n where n is an integer. The value is set in the shared memory segment after the last value already available. If no space is available any more, the program waits for space to be freed by the second program. 2.2. The second program, consumer, does NOT take any argument and returns the first value saved in the shared memory segment. If no value is available, the program will wait for the producer to store a value. Please note that all consumers must share the index of the first saved value. Similarly, all producers must share the index of the first free space. The shared memory segment thus contains both indices. They are critical variables that need to be protected through mutual exclusion semaphores. .

За каждое упражнениеПромежуточные версии работающей программы, с запущенным кодом + вывод трассы выполнения + объяснение каждого шагаПолная версия работающей программы, с запущенным кодом + вывод трассы выполнения + объяснение каждого шага

1. Упражнение 1 Напишите программу, содержащую два процесса: 1.1. Первый процесс инициализирует сегмент общей памяти и группу из двух семафоров. Он создает процесс сына, затем читает все данные в сегменте и печатает их. 1.2. Процесс son вычисляет данные, используя функцию вычисления, которая возвращает 0, когда вычисляются все данные. Он передает их отцу через сегмент общей памяти. Чтобы записать данные, сын делает P на первом семафоре, записывает данные и делает V на втором семафоре. Симметрично отец делает P на втором семафоре, читает данные и делает V на первом семафоре.

  1. Упражнение 2. Основываясь на предыдущем упражнении, напишите две программы. 2.1. Первая программа называется следующим образом: producer n где n - целое число Значение устанавливается в сегменте совместно используемой памяти после последнего доступного значения. Если свободного места больше нет, программа ожидает освобождения места второй программой. 2.2. Вторая программа, consumer , NOT принимает никаких аргументов и возвращает первое значение, сохраненное в сегменте разделяемой памяти. Если значение недоступно, программа будет ждать, пока производитель сохранит значение. Обратите внимание, что все потребители должны использовать индекс первого сохраненного значения. Точно так же все производители должны делиться индексом первого свободного места. Таким образом, сегмент общей памяти содержит оба индекса. Они являются критическими переменными, которые необходимо защищать с помощью семафоров взаимного исключения.

https://www.youtube.com/watch?

v=TYnNKdf7cZM&list=PLypxmOPCOkHXbJhUgjRaV2pD9MJkIArhg&index=

Write a C program that illustrates two

processes communicating using shared

memory.

AIM:

Write a C program that illustrates two processes communicating using shared memory.

Program:

#include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/shm.h> Struct country { Char name[30]; Char capital_city [30]; Char currency[30]; Int population; }; Int main(int argc,charargv[]) { Int shm_id; Charshm_addr; Intcountries_num; Struct countrycountries; Struct shmid_ds shm_desc; Shm_id=shmget(100,2048,IPC_CREAT|IPC_EXCL\0600); If(shm_id==-1){ Perror(“main:shmget:”); Exit(1); } Shm_addr=shmat(shm_id,NULL,0); If(!shm_addr){ Perror(“main:shmat:”); Exit(1); } Countries_num=(int)shm_addr; countries_num=0; Countries=(struct country)((void)shm_addr sizeof(int)); Strcpy(countries[0],name,”U.S.A”); Strcpy(countries[0],capital_city,”WASHINGTON”); Strcpy(countries[0],currency,”U.S.DOLLAR”); Countries[0].population=250000000; ( countries_num) ; Strcpy(countries[1].name,”israel”); Strcpy(countries[1].capital_city,”jerushalem”);