2016-11-26 3 views
1
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include "display.h" 
#include <sys/ipc.h> 
#include <sys/sem.h> 

int main() 
{ 
    int i; 
    struct sembuf up = {0,1,0}; 
    struct sembuf down = {0,-1,0}; 
    int sem0 = semget(IPC_PRIVATE,1,0600); 
    int sem1 = semget(IPC_PRIVATE,1,0600); 
    if (fork()) 
    { 
     for (i=0;i<10;i++) 
      display("ab"); 
      semop(sem1,&up,1); 
      semop(sem0,&down,1); 
      wait(NULL); 
    } 
    else 
    { 
     for (i=0;i<10;i++) 
      semop(sem1,&down,1); 
      display("cd\n"); 
      semop(sem0,&up,1); 
      semop(sem1,&down,1); 
    } 
    semctl(sem0,0,IPC_RMID); 
    semctl(sem1,0,IPC_RMID); 
    return 0; 
} 

mit Ich möchte die Ausgabe
abcd
abcd
abcd
...
Statt der verschlüsselten Ausgabe ich ohne die Semaphore erhalten werden. Der obige Code ist, was ich bisher gemacht habe, aber es scheint nicht zu funktionieren, da ich die Höhen und Tiefen nicht richtig platziere, nehme ich an. Ich bin neu in der gesamten Prozess-Synchronisation und Mutex-Thema und das ist Teil einer Übung, so dass nicht-Semaphor bezogenen Code nicht geändert werden kann. Wenn Sie auf Ihre Antworten eingehen können, wäre das großartig.Output Synchronisation sys Semaphore

EDIT: Das ist die Anzeigefunktion aus der Header-Datei, falls erforderlich.

Antwort

0

Es gibt einige Probleme in Ihrem Code und bitte beachten Sie die Kommentare im Code für die Beschreibung.

int main() 
{ 
    int i; 
    struct sembuf up = {0,1,0}; 
    struct sembuf down = {0,-1,0}; 
    int sem0 = semget(IPC_PRIVATE,1,0600); 
    int sem1 = semget(IPC_PRIVATE,1,0600); 
    if (fork()) 
    { 
     for (i=0;i<10;i++) 
     { 
      display("ab"); 
      semop(sem1,&up,1); 
      semop(sem0,&down,1); 
      //wait(NULL); //MAYUR: wait() suspends the execution until one of its children terminates. But this was unnecessary here. I removed it. 
     } //MAYUR: There was no brackets for "for loop". Added it in both the blocks. 
    } 
    else 
    { 
     for (i=0;i<10;i++) 
     { 
      semop(sem1,&down,1); 
      display("cd\n"); 
      semop(sem0,&up,1); 
      //semop(sem1,&down,1); //MAYUR: You are doing wait for sem1 in two places. This is was leading to deadlock. Removed it. 
     } 
    } 
    semctl(sem0,0,IPC_RMID); 
    semctl(sem1,0,IPC_RMID); 
    return 0; 
} 

Ausgang:

abcd 
abcd 
abcd 
abcd 
abcd 
abcd 
abcd 
abcd 
abcd 
abcd