tu to mas cele :
Kód:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
//#include "shm_com.h"
union semun
{ int val, arg1, arg2; /* hodnota pre SETVAL */
struct semid_ds *buf; /* buffer pre IPC_STAT, IPC_SET */
unsigned short int *array; /* pole pre GETALL, SETALL */
struct seminfo *__buf; /* buffer pre IPC_INFO */
};
static int set_semvalue(void);
static void del_semvalue(void);
static int semaphore_p(void);
static int semaphore_v(void);
static int sem_id;
int main()
{
int i;
int pause_time;
char op_char = 'X';
srand((unsigned int)getpid());
int running = 1;
void *shared_memory = (void *)0;
struct shared_use_st *shared_stuff;
int shmid;
srand((unsigned int)getpid());
sem_id = semget((key_t)1284, 1, 0666 | IPC_CREAT);
if(sem_id==-1){
perror("semget()");
exit(EXIT_FAILURE);
}
printf("Program sem1.c ID semaforu: %d\n",sem_id);
if (!set_semvalue()) {
fprintf(stderr, "Failed to initialize semaphore\n");
exit(EXIT_FAILURE);
}
shmid = shmget(1294,sizeof( shared_use_st),0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid, (void *)0, 0);
if (shared_memory == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X\n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
sleep(2);
while(running) {
if (!semaphore_p()) exit(EXIT_FAILURE);
printf("You wrote: %s\n", shared_stuff->some_text);
if (!semaphore_v()) exit(EXIT_FAILURE);
if (strncmp(shared_stuff->some_text, "end", 3) == 0) {
running = 0;
}
sleep(1);
}
del_semvalue();
if (shmdt(shared_memory) == -1) {
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
static int set_semvalue(void){
union semun sem_union;
sem_union.val = 1;
if (semctl(sem_id, 0, SETVAL, sem_union) == -1) return(0);
return(1);
}
static void del_semvalue(void){
if (semctl(sem_id, 0, IPC_RMID) == -1)
fprintf(stderr, "Failed to delete semaphore\n");
}
static int semaphore_p(void)
{
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = -1;
sem_b.sem_flg = SEM_UNDO;
if (semop(sem_id, &sem_b, 1) == -1) {
fprintf(stderr, "semaphore_p failed\n");
return(0);
}
return(1);
}
static int semaphore_v(void)
{
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = 1;
sem_b.sem_flg = SEM_UNDO;
if (semop(sem_id, &sem_b, 1) == -1) {
fprintf(stderr, "semaphore v failed\n");
return(0);
}
return(1);
}