2017-11-25 190 views
1

我有簡單的生產者消費者程序在C嘗試用fork解決它 生產者試圖在管道上寫入時我得到錯誤: 我已經寫了另一個程序具有相同的邏輯,但這一個不知道爲什麼?C管道:錯誤的文件描述符

生產者未能寫管道項目:爲什麼我得到這個錯誤,錯誤的文件描述符

任何人有想法? 由於

#define READ 0 
#define WRITE 1 
int mutex = 1, full = 0, empty = BUFFER_SIZE, x = 0; 

void consumer(); 

void producer(); 

int wait_(int); 

int signal_(int); 

int pipefd[2]; 

int main() { 
    printf("Starting producer-consumer problem!\n"); 
    //We intend to run the producer in parent process and the consumer in the child process 
    if (pipe(pipefd) == -1) {  /* An error has occurred. */ 
     fprintf(stderr, "%s", "The call to pipe() has failed.\n"); 
     exit(EXIT_FAILURE); 
    } 
    for (int j = 0; j < sizeof(pipefd); j++) { 
     if (pipe(&pipefd[j]) < 0) { //Initialize each pipe appropriately 
      perror("Error in making pipe..."); 
     } 
    } 
    pid_t pid = fork(); 
    if (pid < 0) { 
     perror("**********Error in creating fork()!**************\n"); 
     exit(STDERR_FILENO); 
    } else if (pid == 0) { 
     consumer();//We intend to run the consumer in child 
    } else { 
     producer();//We intend to run the producer in parent 
    } 
    return 0; 
} 

int wait_(int s) { 
    return (--s); 
} 

int signal_(int s) { 
    return (++s); 
} 

void producer() { 
    printf("Starting Producer\n"); 
    //while (1) { 
    //sleep(1); 
    if (close(pipefd[READ]) != 0) { 
     perror("Error in closing reading pipe"); 
    } 
    if (write(pipefd[WRITE], &full, 1) < 0) { 
     perror("Producer failed to write item on pipe"); 
    } 
    if ((mutex == 1) && (empty != 0)) { 
     mutex = wait_(mutex); 
     full = signal_(full); 
     empty = wait_(empty); 
     x++; 
     printf("Producer produces the item %d\n", x); 
     mutex = signal_(mutex); 
    } 
    if (close(pipefd[WRITE]) != 0) { 
     perror("Error in closing writing pipe"); 
    } 
    //} 
} 

void consumer() { 
    printf("Starting Consumer\n"); 
    //while (1) { 
    //sleep(1); 
    int status = 0; 
    wait(&status);    /* wait for all children to return back the result */ 
    if (close(pipefd[WRITE]) != 0) { 
     perror("Error in closing reading pipe"); 
    } 
    if (read(pipefd[READ], &full, 1) > 0) { 
     printf("Consumer\t%d\n", full); 
    } 
    if ((mutex == 1) && (full != 0)) { 
     mutex = wait_(mutex); 
     full = wait_(full); 
     empty = signal_(empty); 
     printf("Consumer consumes item %d\n", x); 
     x--; 
     mutex = signal_(mutex); 
    } 
    if (close(pipefd[READ]) != 0) { 
     perror("Error in closing reading pipe"); 
    } 
    //} 
} 
+0

「READ」和「WRITE」定義在哪裏? – Frxstrem

+0

什麼是REAd&WRITE值?它是0&1嗎? – achal

回答

1

sizeof操作者以字節返回該尺寸。因此,在int爲四個字節的典型系統中,sizeof(pipefd)將產生值8。這不是你的循環的正確數量的元素。

另外,pipe(&pipefd[j])也不正確。 pipefd中的兩個管道已經已經「適當」初始化。不需要任何更多的初始化。特別是因爲在這個和以前的情況下,你將有undefined behavior

+0

謝謝!這解決了我的問題。調用pipe(pipefd)進行初始化足夠了嗎? – matio

+0

@Metao就是夠了。 –

+0

再次感謝您。是否必須關閉管道的寫入描述符?如何在迭代器中做到這一點,並確保我們不關閉兩次? – matio