Hi,
I have added sleep with random timings and printed the values.
I am actually expecting the "Blocked in Child" OR "Blocked in Parent" out put when other process sleeps.
But it it never printing the statement.(when the process is going to sleep the semaphore is not cleared so i expect sem unavailable)
can some one please modify my program so that it is blocked atleast once in course of execution.
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(int argc, char **argv)
{
int fd, i,count=0,nloop=10,zero=0,*ptr;
sem_t mutex;
//open a file and map it into memory
fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU);
write(fd,&zero,sizeof(int));
ptr = mmap(NULL,sizeof(int),PROT_READ |PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
/* create, initialize semaphore */
if( sem_init(&mutex,1,1) < 0)
{
perror("semaphore initilization");
exit(0);
}
if (fork() == 0) { /* child process*/
if ( -1 != sem_wait(&mutex) ) {
for (i = 0; i < nloop; i++) {
printf("child: %d\n", (*ptr)++);sleep(10);
sem_post(&mutex);
}
}
else {
printf("Blocked in Parent\n");
}
exit(0);
}
/* back to parent process */
if ( -1 != sem_wait(&mutex)) {
for (i = 0; i < nloop; i++) {
printf("parent: %d\n", (*ptr)++);sleep(5);
sem_post(&mutex);
}
} else {
printf("Blocked in Child");
}
exit(0);
}
Thanks,
Gaiety.