这是我的代码:
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;
}
输出变为:
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 childs 执行不同进程的正确方法吗?
PS对不起,我的英语不好。我希望你能明白我说的话。