Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.
Some of the corrections you must make are:
1) You must make a variable of semaphore type
sem_t semvar;
2) The functions sem_wait()
, sem_post()
require the semaphore variable but you are passing the semaphore id, which makes no sense.
sem_wait(&semvar);
//your critical section code
sem_post(&semvar);
3) You are passing the semaphore to sem_wait()
and sem_post()
without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.
ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
perror("Semaphore failed to initialize");
Study the semaphore API's from the man page and go through this example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…