這是我的代碼:如何fork()n子進程執行不同的功能?
for (c = 0; c < PROCESSES; c++) {
pid[c] = fork();
switch (pid[c]) {
case -1:
perror("Faild fork!\n");
break;
case 0:
printf("C = %d\n", c);
if (c == 0) {
printf("MY ID0 %d\n", getpid());
customers();
break;
}
if (c == 1) {
printf("MY ID1 %d\n", getpid());
cashier();
break;
}
if (c == 2) {
printf("MY ID2 %d\n", getpid());
sales();
break;
}
if (c == 3) {
printf("MY ID3 %d\n", getpid());
warehouse();
break;
}
break;
default:
if (c == (PROCESSES - 1)) {
for (j = 0; j < PROCESSES; j++) {
w = wait(&state);
if (w == -1) {
perror("Erro na espera!\n");
}
printf("Terminar processo %d\n", w);
}
sleep(2);
printf("Fim da simulação.\n\n");
free_shm_sem();
}
}
}
我期待發生:
C = 0
MY ID0 3904
C = 1
MY ID1 3905
C = 2
MY ID2 3906
C = 3
MY ID3 3907
發生了什麼:
C = 0
MY ID0 3904
C = 1
MY ID1 3905
C = 2
MY ID2 3906
C = 3
MY ID3 3907
C = 3
MY ID3 3911
如果我更改爲:
if (c == 0) {
printf("MY ID0 %d\n", getpid());
customers();
break;
}
if (c == 1) {
printf("MY ID1 %d\n", getpid());
sales();
break;
}
if (c == 2) {
printf("MY ID2 %d\n", getpid());
cashier();
break;
}
if (c == 3) {
printf("MY ID3 %d\n", getpid());
warehouse();
break;
}
釷e的輸出變成:
C = 0
C = 2
C = 1
MY ID0 3960
MY ID2 3962
C = 3
MY ID1 3961
MY ID3 3963
C = 2
MY ID2 3967
C = 3
MY ID3 3968
爲什麼c改變它的值,有時兩次通過相同的地方?
這不是fork()n孩子做不同過程的正確方法嗎?
P.S.對不起,我的英語不好。我希望你能理解我說的話。
我不希望它順序運行。但我不想重複的過程,如果你明白... –