2013-05-14 71 views
1

我想寫一個程序,分叉另一個進程並保持同步,以便第一個進程不會開始其第(i)次迭代,直到第二個進程完成其(i-1)迭代。這可能只使用兩個信號量嗎?這是我到目前爲止有:意外的輸出運行信號量

#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <semaphore.h> 

sem_t semA, semB,sem,m; 

int main(void) 
{ 
int i; 

    pid_t child_a, child_b,pid2,pid3; 
    sem_init(&semA, 0, 1); 
    sem_init(&semB, 0, 0); 
sem_init(&m, 0, 0); 

    child_a = fork(); 
//wait(); 

    if (child_a == 0) { 


    // int j; 

     pid2 =getpid(); 
     for (i = 0; i < 5;) 
     { 
    sem_wait(&semA); 
//sem_wait(&m); 
     printf("child1: %d\n", i); 
    i++; 
    //printf("pid1: %d\n", pid2); 
     //printf("--------------------------\n"); 
     sleep(3); 
//sem_post(&m); 

sem_post(&semB); 
     } 
}  
    else { 

    child_b = fork(); 
//wait(); 
    if (child_b == 0) { 

     pid3 =getpid(); 
     for (i = 0; i < 5;) 
     { 
sem_wait(&semB); 
//sem_wait(&m); 
     printf("child2: %d\n", i); 
i++; 
     //printf("pid2: %d\n", pid3); 
     //printf("--------------------------\n"); 
     sleep(5); 
//sem_post(&m); 
sem_post(&semA); 

     } 

    } 
    } 

    exit(0); 
    return 0; 
} 

我期望的輸出是:

child1: 0 
child2: 0 
child1: 1 
child2: 1 
child1: 2 
child2: 2 
child1: 3 
child2: 3 
child1: 4 
child2: 4 
child1: 5 
child2: 5 
child1: 6 
child2: 6 
child1: 7 
child2: 7 
child1: 8 
child2: 8 
child1: 9 
child2: 9 

,但我得到的只是一個孩子:

child1: 0 
+0

[Unexpected Output Running Semaphore]的可能重複(http://stackoverflow.com/questions/16549718/unexpected-output-running-semaphore) – Mat 2013-05-14 18:18:10

+0

請**不要**交叉帖子。然後你在一個網站上得到重複的問題。這根本不是最優的,而且浪費了每個人的時間。選擇一個網站。如果您認爲您選擇了錯誤的網站,請求遷移(通過標記您的帖子並解釋您在「其他」文本框中所需的內容)。 – Mat 2013-05-14 18:19:32

+0

這(SO 16549939)不能是SO 16549718的重複,因爲'718已經作爲'939的重複項被關閉了。 – 2014-05-05 03:42:07

回答

0

您可能需要three semaphores

SEM1 sem2 sem3

處理1:

if(FirstRun){ 
    Initialize the semaphores 
    wait for sem2 
} 

post sem1 
wait for sem3 

進程2:

if(FirstRun){ 
    Initialize the semaphores 
    post sem2 
} 

wait for sem1 
post sem3 

注意:在Initialize the semaphores你必須將信號量映射到shared memory,以便兩個進程都可以訪問。還要將它們初始化爲默認值0, 0, 0