Note that there are some explanatory texts on larger screens.

plurals
  1. POsimple testing of semaphores
    primarykey
    data
    text
    <p>I am trying to create a simple program to test semaphores. I am forking the process and tormenting the value of variable c in the critical section of each process, but the value of c I get is still 1 not 2. Even with the mmap() uncommented. Can anyone please explain to me what I am doing wrong? Any help would be appreciated. I am a total newbie in this. Thank you very much for your time.</p> <pre><code>int main() { int c = 0; sem_t mutex; sem_t mutex1; // sem_t *mutex = (sem_t*)mmap(NULL, sizeof(sem_t*), PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); sem_init(&amp;mutex, 0, 1); sem_init(&amp;mutex1, 0, 1); pid_t i; int id = fork(); if(id == -1) {} else if(id == 0) { sem_wait (&amp;mutex); c++; sem_post (&amp;mutex); } else { sem_wait (&amp;mutex); c++; sem_post (&amp;mutex); } cout&lt;&lt;c&lt;&lt;endl; //system("pause"); return 0; } </code></pre> <p>I tried it another way by making the pshared argument 1, but it still does not work. I have also tried it sem_op but it still does not work.</p> <pre><code> int main() { int c = 0; int sid =semget(1105,2, 0666 | IPC_CREAT); pid_t i; int id = fork(); if(id == -1) { } else if(id == 0) { struct sembuf sb; sb.sem_num = 0; sb.sem_op = -1; sb.sem_flg = 0; if((semop(sid, &amp;sb, 1)) == -1) cout&lt;&lt;"error"&lt;&lt;endl; c++; sb.sem_num = 0; sb.sem_op = -1; sb.sem_flg = 0; if((semop(sid, &amp;sb, 1)) == -1) cout&lt;&lt;"error"&lt;&lt;endl; } else if(id == 1) { struct sembuf sb; if((semop(sid, &amp;sb, 1)) == -1) cout&lt;&lt;"error"&lt;&lt;endl; c++; sb.sem_num = 0; sb.sem_op = -1; sb.sem_flg = 0; if((semop(sid, &amp;sb, 1)) == -1) cout&lt;&lt;"error"&lt;&lt;endl; } cout&lt;&lt;c&lt;&lt;endl; return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload