1
I am trying to create 3 processes and use semaphore on them. The code below compiles, but in the middle of the execution there is an error called "Segmentation fault". I don’t know how to solve this. I appreciate the patience. The goal is to create a semaphore that could be shared by the 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;
}
}
I recommend to you to look at the return of the methods of creation and initialization of the semaphore, they return errors that can help you to understand the
segfault
which occurs in the use of the semaphore. From a look at: http://man7.org/linux/man-pages/man3/sem_open.3.html and http://man7.org/linux/man-pages/man3/sem_init.3.html– Wakim