I'm trying to create 3 processes and use semaphore in them. The code below compiles, but in the middle of the execution there is an error called "segmentation fault". I do not know how to solve this. Thank you for your patience. The goal is to create a semaphore that could be shared by processes.
#include <pthread.h>
#include <semaphore.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>
void F1(){
printf("F1\n");
sem_t *sem;
sem = sem_open("mysem", O_CREAT, 0600, 0);
sem_init(sem,1,1);
for(;;){
sem_wait(sem);
printf("Filosofo 1 - Vou executar 10 segundos\n");
sleep(10);
sem_post(sem);
}
}
void F2(){
printf("F2\n");
sem_t *sem;
sem = sem_open("mysem", O_CREAT, 0600, 0);
sem_init(sem,1,1);
for(;;){
sem_wait(sem);
printf("Filosofo 2 - Vou executar 10 segundos\n");
sleep(10);
sem_post(sem);
}
}
void F3(){
printf("F3\n");
printf("F3\n");
sem_t *sem;
sem = sem_open("mysem", O_CREAT, 0600, 0);
sem_init(sem,1,1);
for(;;){
sem_wait(sem);
printf("Filosofo 3 - Vou executar 10 segundos\n");
sleep(10);
sem_post(sem);
}
}
int main(int arc, char *argv[]){
int i, n=3;
for(i=0; i<n; i++) {
if(i == 0){
printf("Fui executado i vez\n",i);
}
if(fork())
break;
}
switch(i) {
case 0:
F1();
break;
case 1:
F2();
break;
case 2:
F3();
break;
}
}