簡體   English   中英

叉中的printf錯誤

[英]Wrong printf in fork

我為我的英語致歉,希望您能理解。 所以我的程序中有一個printf的問題,它等待父親的結束和一些在printf之前的時間。 因此,我總是得到父親來打印所有消息,然后兒子將所有消息打印出來,而應該將其刪除。

從我所看到的,我讀到我必須得臉紅,但這並不能解決我的問題。 謝謝您的幫助。 這是我的代碼。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <sys/shm.h>

int cpt = 0;

void fils(int *cpt){
  int i;
  for(i = 0; i < 3; i++){
    (*cpt)++;
    printf("son : %d\n", *cpt);
  }
}

void pere(int *cpt){
  int i;
  for(i = 0; i < 3; i++){
    (*cpt)--;
    printf("father : %d\n", *cpt);
    fflush(stdout);
  }
}

int main (int argc, char*argv[]){
  key_t key;
  int memShared;
  int *cpt = NULL;

  key = ftok(argv[0],'p');
  memShared = shmget(key, sizeof(int), IPC_CREAT|IPC_EXCL|0666);
  cpt = shmat ( memShared, cpt, 0);
  *cpt = 0;

  fflush(stdout);
  switch (fork()){
    case -1: perror("erreur de création du fils");
         exit(99);
    case  0: fils(cpt);
         exit(1);
    default: pere(cpt);
         wait(NULL);
  }
   shmctl(memShared, IPC_RMID, NULL);

  return 0;
}

我總是在終端上有這個

父親:-1父親:-1父親:-2兒子:0兒子:-1兒子:0

我雖然應該越過,例如父親:-1兒子:0父親:-1 ...感謝您的幫助。

這是一場經典比賽。 要實現“先到先得”的順序,只需在switch重新排列行:

switch (fork()){
case -1: perror("erreur de création du fils");
     exit(99);
case  0: fils(cpt);
     exit(1);
default: wait(NULL); //First - wait
     pere(cpt);      //Then - print   
}

您無法保證這種簡單的解決方案是否會按預期工作。 您想要的是確保一個進程只執行一次循環迭代,直到將其關閉為止。

如果要確保它們以這種ABABAB方式運行,則需要另一種同步機制。 請記住,簡單的信號量是不夠的。 您可能需要一個管道或一個fifo隊列,以允許該進程進行通信。 查找稱為pipemkfifo函數。 比您可以這樣:

for(number_of_iterations)
{
   wait for a message from the other process;
   do work on shm;
   send message to another process, allowing it to continue;
}

這將激發令牌的概念。

至於注釋中的建議:將派生結果保留在變量a中,然后在有更多進程時使用waitpid等待更為安全,因為wait等待第一個結束進程,而不是特定的進程。

chenchongyf1@chenchongyf1:~$
chenchongyf1@chenchongyf1:~$ ./wrong_printf
father : -1
son : 0
son : 1
son : 2
father : 1
father : 0
chenchongyf1@chenchongyf1:~$** 

該程序可以在我的計算機上運行。 我的意思是父親的兒子和兒子的兒子確實是交叉的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM