【发布时间】:2015-02-21 23:12:44
【问题描述】:
我有这个 C 代码序列:
printf("\nThe PID of this (main) process is: %d\n", getpid());
if(fork() != -1) { // #1
printf("\n\nParent 1 PID: %d\n", getpid());
for(int i = 0; i < 10; i++) {
printf("\n%d", i);
}
if(fork() != -1) { // #2
//sleep(1);
printf("\n\nParent 2 PID: %d\n", getpid());
for(char i = 'a'; i != 'f'; i++) {
printf("\n%c", i);
}
}
else { // #3
sleep(3);
printf("\n\nChild 2 PID: %d\n", getpid());
for(char i = 'F'; i != 'J'; i++) {
printf("\n%c", i);
}
}
}
else { // #4
sleep(4);
printf("\n\nChild 1 PID: %d\n", getpid());
for(int i = 10; i < 20; i++) {
printf("\n%d", i);
}
}
我希望我将有 4 个进程:两个父母和两个孩子。
在第 1 行,我第一次调用 fork(),从第 1 行到第 4 行的所有内容都将在第一个父进程中执行。
在父进程 (1) 中,我再调用一次fork(),因此从第 2 行到第 3 行,我将拥有父 2 进程,从第 3 行到第 4 行,我将拥有子 2 进程。
我期望打印的内容:
Parent 1 PID: ....
0
1
2
3
4
5
6
7
8
9
Parent 2 PID: ....
a
b
c
d
e
Child 2 PID: ....
F
G
H
I
Child 1 PID: ....
10
11
12
13
14
15
16
17
18
19
我实际上得到了什么:
Parent 1 PID: 3877
0
1
2
3
4
5
6
7
8
Parent 1 PID: 3878
0
1
2
3
4
5
6
7
8
9
Parent 2 PID: 3877
a
b
c
d
e9
Parent 2 PID: 3878
9
a
b
c
d
Parent 2 PID: 3879
a
b
c
d
e9
eParent 2 PID: 3880
a
b
c
d
e
我做错了什么?
【问题讨论】:
-
fork() != -1检查什么? -
如果调用失败,返回-1。所以我检查调用是否没有失败。
-
那么
else块有什么作用? -
e9s 是由于倒退的printfs。将\n放在printfs 的末尾可以解决这个问题。 -
@Oliver Charlesworth 好吧,现在我看到了问题:如果调用失败,
if语句变为 false,然后else语句将被执行。