2017-04-05 92 views
0

比方說,我有3個進程,包括父進程我必須按P3,P1,P2的順序執行I程序。夥計們請幫我一下,我怎樣才能從P3進程開始計算。如何使用信號量同步進程

我需要出去爲{0,1,2,3,4,5,... MAX}

對於參考我的代碼快照是: -

#define SEM_NAME "//test.mutex" 
//#define SEM_NAME2 "//test2.mutex" 

int main(int argc, char const *argv[]) { 
    int max = 0, i =0; 
    sem_t *sem; 
    sem_t *sem2; 
    pid_t pid, pid2; 
    sem = sem_open(SEM_NAME, O_CREAT, O_RDWR, 1); 
    sem_unlink(SEM_NAME); 
    if (sem==SEM_FAILED) { 
    printf("%s sem_open failed!", SEM_NAME); 
    return (-1); 
    } 
    // sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 0); 
    // sem_unlink(SEM_NAME2); 
    // if (sem2==SEM_FAILED) { 
    // printf("%s sem_open failed!", SEM_NAME2); 
    // return (-1); 
    // } 
    printf("Enter the maximum number\n"); 
    scanf("%d", &max); 
    pid = fork(); 
    if(pid == 0) 
    { 
    i = 2; 
    pid2 = fork(); 
    if(pid2 == 0) 
    { 
     i = 0; 
    } 
    else 
    { 
     sleep(2); 
    } 
    } 
    else 
    { 
    i = 1; 
    sleep(1); 
    } 
    //do 
    { 
    sem_wait(sem); 
    for (; i <= max;) { 
     printf("pid %d done and value is %d\n", getpid(),i); 
     i = i + 3; 
    } 
    sem_post(sem); 
    } //while(i <= max); 
    wait(NULL); 
    return 0; 
} 

當我運行程序我得到如下輸出 {0,3,,6,1,4,7,2,5,8}

我需要一種方式,我第一個進程應該打印一個數字,它應該讓其他進程打印他的號碼和最後三分之一應該打印。

我需要一種方式,每個和那裏順序轉向。

希望我這樣一個問題明確

回答

0

這裏是如何可以實現順序P3,P1僞代碼,P2

//semaphores for P1, P2, P3 respectively 
semaphore s1=0; 
semaphore s2=0; 
semaphore s3=1;  //coz P3 needs to go first 


//for p3 
wait(s3) 
    //do p3 here 
signal(s1)   //signal for P1 to start 


//for p1 
wait(s1) 
    //do p1 
signal(s2)   // signal to start P2 


//for p2 
wait(s2) 
    //do p2 
signal(s3)   //signal to start p3 again if that is required or you can omit this if not required