Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#include <iostream>
#include <unistd.h>
#include <ctime>
#include <cstdlib>
#include <signal.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <semaphore.h>
using namespace std;
#define MAX_PROCESSES 7
#define MAX_SEMAPHORES 7
int Id;
struct sharedSpace
{
sem_t* binarySemaphores[MAX_SEMAPHORES];
};
sharedSpace* segment;
void process(int processNr)
{
srand(time(0));
int duration = rand()%10;
int currentNumberOfSeconds = 0;
for (int i = 0; i < duration; i++)
{
sleep(1);
currentNumberOfSeconds++;
cout << "Izvodim proces " << processNr << ": "
<< currentNumberOfSeconds << "/" << duration << endl;
}
}
int main()
{
// stvaranje procesa
int processNr = 1;
// zajednicki mem prostor
Id = shmget(IPC_PRIVATE,sizeof(sharedSpace)*100, 0600);
if (Id == -1)
{
cout << "Shared memory allocation failed."
<< endl;
return -1;
}
segment = (sharedSpace*) shmat(Id, NULL, 0);
for (int i = 0; i < MAX_SEMAPHORES; i++)
{
sem_init(*segment->binarySemaphores[i], 1, 0); // error: cannot convert 'sem_t' to 'sem_t*' for argument '1' to 'int sem_init(sem_t*, int, unsigned int)'
}
for (int i = 0; i < MAX_PROCESSES; i++)
{
if (fork() == 0)
{
process(processNr);
exit(0);
}
processNr++;
}
for (int i = 0; i < MAX_PROCESSES; i++)
{
wait(NULL);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment