-
Semaphore Question
Hi,
I am making a semaphore application. I make a child process which waits for the semaphore object to be free from the main process. And when its free than it accesses it.
For some reason its not printing the correct result:
What I want is that child process should wait for the semaphore to be free from the main process and when its free it accesses it. But for some reason it goes to the child process and prints out the values without waiting for the semaphore to be free
Code:
semid = CreateSemaphore(key,1,vals);
// Begin the process and wait for the semaphore
pid = fork();
if(pid == 0) // CHILD PROCESS
{
NEWLINE;
printf("Process begins and wait for the semaphore");
sops[0].sem_num = 0; /* We only use one track */
sops[0].sem_op = -1; /* wait for semaphore flag to become zero */
sops[0].sem_flg = 0; /* take off semaphore asynchronous */
sleep(6);
semop(semid,&sb,1);
NEWLINE;
printf("Process enters the semaphore");
}
else // Main Process
{
sleep(5);
NEWLINE;
printf("Parent Releases the Semaphore");
sops[0].sem_num = 0;
sops[0].sem_op = 1; // releases the semaphore
sops[0].sem_flg = 0;
}
-
Is a semaphore a kernel object? You might want to use a mutex, I know that's a kernel object.
-
Hi,
Thanks for the reply. Well, but should'nt it automatically assign the semaphore object to the process that is waiting for it. I code this thing in C# (C Sharp) using Semaphore Class and it worked smoothly. I am not sure seems like I am missing something. I need to release the semaphore object from the main method and than other processes will be able to access it.
-
well, it may be different. I don't know a whole lot about using fork, but if it creates another process and not just another thread then you may need a mutex. In your C# program, did you create another process or did you just create another thread?
-
In my c# application I created a new THREAD. I guess I do have to use Mutex.
Thanks for the advice!