 Esercizio Sleep-Sort con semafori
 Esercizio Sleep-Sort con semafori
Posted by richard.greco on 09-05-2015 18:08
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <sys/wait.h>
#include <sys/stat.h>
int main(){
	int ID = shmget(IPC_PRIVATE, sizeof(sem_t), S_IRUSR | S_IWUSR), i, j=0;
	sem_t *mutex = (sem_t * )shmat(ID, NULL, 0);
	sem_init(mutex, 0, 0);
	pid_t pid;
	
	printf("Inserire numero (terminare con 0): ");
	scanf("%d", &i);
	while(i!=0){
		j++;
		if((pid = fork())==0){
			printf("\nSto aspettando pid=%d, i=%d\n", getpid(), i);
			sem_wait(mutex);
			sem_post(mutex);
			printf("\nVado pid=%d, i=%d\n", getpid(), i);
			sleep(i);
			printf("%d ", i);
			shmdt(mutex);
			return 0;
		}
		printf("Inserire numero (terminare con 0): ");
		scanf("%d", &i);
	}
	
	printf("\npadre?");
	sem_post(mutex);
	
	for(i=0; i<j; i++)
		wait(NULL);
	printf("\n");
	sem_destroy(mutex);
	shmdt(mutex);
	shmctl(ID, IPC_RMID, NULL);
	return 0;
}
Non capisco come mai non funziona, qualcuno saprebbe aiutarmi? in sostanza il processo padre non esce dal while e non raggiunge mai il "sem_post", che sbloccherebbe tutti i figli.  Non raggiunge neanche la printf addirittura.
Powered by: vbHome (lite) v3.8 and vBulletin v2.3.1
Copyright © 2000 - 2002 Jelsoft Enterprises Limited