My program gets a segmentation fault when I run it normally.
However, it works just fine if I use gdb run
. Moreover, the ratio of segmentation fault increases when I increase the sleep time in the philo function. I am using Ubuntu 12.04 (Precise Pangolin). Here is my code:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>
#include <semaphore.h>
#include <errno.h>
#define STACKSIZE 10000
#define NUMPROCS 5
#define ROUNDS 10
int ph[NUMPROCS];
// cs[i] is the chopstick between philosopher i and i+1
sem_t cs[NUMPROCS], dead;
int philo() {
int i = 0;
int cpid = getpid();
int phno;
for (i=0; i<NUMPROCS; i++)
if(ph[i] == cpid)
phno = i;
for (i=0; i < ROUNDS ; i++) {
// Add your entry protocol here
if (sem_wait(&dead) != 0) {
perror(NULL);
return 1;
}
if (sem_wait(&cs[phno]) != 0) {
perror(NULL);
return 1;
}
if (sem_wait(&cs[(phno-1+NUMPROCS) % NUMPROCS]) != 0) {
perror(NULL);
return 1;
}
// Start of critical section -- simulation of slow n++
int sleeptime = 20000 + rand()%50000;
printf("philosopher %d is eating by chopsticks %d and %d\n", phno, phno, (phno - 1 + NUMPROCS)%NUMPROCS);
usleep(sleeptime);
// End of critical section
// Add your exit protocol here
if (sem_post(&dead) != 0) {
perror(NULL);
return 1;
}
if (sem_post(&cs[phno]) != 0) {
perror(NULL);
return 1;
}
if (sem_post(&cs[(phno - 1 + NUMPROCS) % NUMPROCS]) != 0) {
perror(NULL);
return 1;
}
}
return 0;
}
int main(int argc, char ** argv) {
int i;
void* stack[NUMPROCS];
srand(time(NULL));
// Initialize semaphores
for (i=0; i<NUMPROCS; i++) {
if (sem_init(&cs[i], 1, 1) != 0) {
perror(NULL);
return 1;
}
}
if (sem_init(&dead, 1, 4) != 0) {
perror(NULL);
return 1;
}
for (i = 0; i < NUMPROCS; i++) {
stack[i] = malloc(STACKSIZE);
if (stack[i] == NULL) {
printf("Error allocating memory\n");
exit(1);
}
// Create a child that shares the data segment
ph[i] = clone(philo, stack[i] + STACKSIZE - 1, CLONE_VM|SIGCHLD, NULL);
if (ph[i] < 0) {
perror(NULL);
return 1;
}
}
for (i=0; i < NUMPROCS; i++)
wait(NULL);
for (i=0; i < NUMPROCS; i++)
free(stack[i]);
return 0;
}