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
semid = CreateSemaphore(key,1,vals);
// Begin the process and wait for the semaphore
pid = fork();
if(pid == 0) // CHILD PROCESS
printf("Process begins and wait for the semaphore");
sops.sem_num = 0; /* We only use one track */
sops.sem_op = -1; /* wait for semaphore flag to become zero */
sops.sem_flg = 0; /* take off semaphore asynchronous */
printf("Process enters the semaphore");
else // Main Process
printf("Parent Releases the Semaphore");
sops.sem_num = 0;
sops.sem_op = 1; // releases the semaphore
sops.sem_flg = 0;
Is a semaphore a kernel object? You might want to use a mutex, I know that's a kernel object.
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!