我們的子進程NUM_PLAYERS
,和他們每個人的輸出其ID喜歡不同的進程寫出同時
player 5: I scored 0 (PID = 411160)
但問題是,所有的人都同時寫出因此它的輸出一團糟。
player player player 1: I'm in this game (PID = 11049)
player 01: I scored 3: I'm in this game (PID = 11051: I'm in this game (PID = 1048)
我該如何讓他們等待對方並寫信?這裏是我的實際代碼
int main(int argc, char *argv[])
{
for (i = 0; i < NUM_PLAYERS; i++) {
/* TODO: spawn the processes that simulate the players */
switch(pid = fork()) {
case -1:
printf("Perror\n");
exit(EXIT_FAILURE);
break;
case 0:
//printf("%s<%d>%s<%d>\n", "CHILD ", getpid(), " ppid: ", getppid());
//sleep(1);
dup2(seedArray[i][0], STDIN_FILENO);
close(seedArray[i][0]);
dup2(scoreArray[i][1], STDOUT_FILENO);
close(scoreArray[i][1]);
sprintf(arg1,"%d",i);
execv("./shooter", args);
//shooter(i, seedArray[i][0], scoreArray[i][1]);
//exit(EXIT_SUCCESS);
break;
default:
//pid = wait(NULL);
pidArray[i] = pid;
}
}
// SOME IRRELEVANT CODE HERE
int status;
for(i = 0;i < NUM_PLAYERS; i++)
{
wait(&status);
}
return 0;
}
請注意,將輸出同步到日誌文件可能會使日誌記錄成爲應用程序的瓶頸。 –