我道歉,但我的英語,我希望你能明白。 所以我有我的程序中的printf這個問題,等待父親的結束和一些printf之前。所以我總是得到父親打印他所有的信息,然後兒子printf他所有的信息,而它應該交叉..錯誤printf在叉
從我看到的,我讀了,我必須有fflush,但它不能解決我的問題。 Thx爲您提供幫助。 這是我的代碼。
#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 ... 感謝您的幫助。
你說「它應該交叉」,但你沒有實現這樣做的機制。這兩個過程都只是爲了寫出所有的輸出,你的程序中沒有任何東西可以讓你等待另一個。如果你想讓他們交替輸出,你必須編寫代碼讓他們做到這一點。你也不會同步對共享內存的訪問,這就是爲什麼你會得到奇數輸出,比如父親連續寫兩個'-1'。 – 2014-10-19 19:17:28
您總是需要將'fork'的結果保存在一個變量中,因爲父親需要'waitpid'。另請參閱[shm_overview(7)](http://man7.org/linux/man-pages/man7/shm_overview.7.html)和[sem_overview(7)](http://man7.org/linux/man -pages/man7/sem_overview.7.html) – 2014-10-19 19:17:38
@BasileStarynkevitch:不需要。他正在等待任何一個子進程完成。這足夠有選擇性。 (我們不是在一般情況下,真正必須使用'waitpid'。) – Deduplicator 2014-10-19 19:21:44