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;
	}