首先,我在Windows 7系统上使用cygwin版本1.7.1。代码是使用gcc编译并从bash提示符中运行的。接下来进入正题:
我正在研究fork()和exec()的工作原理,因此我查看了维基百科。在那里,我找到了以下简单的C代码,用于进行一些fork-on-fork操作:
#include <stdio.h> /* printf, stderr, fprintf */
#include <unistd.h> /* _exit, fork */
#include <stdlib.h> /* exit */
#include <errno.h> /* errno */
int main(void)
{
pid_t pid;
/* Output from both the child and the parent process
* will be written to the standard output,
* as they both run at the same time.
*/
pid = fork();
if (pid == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(EXIT_FAILURE);
}
if (pid == 0)
{
/* Child process:
* When fork() returns 0, we are in
* the child process.
* Here we count up to ten, one each second.
*/
int j = 0;
for (j = 0; j < 10; j++)
{
printf("child: %d\n", j);
sleep(1);
}
_exit(0); /* Note that we do not use exit() */
}
else
{
/* Parent process:
* When fork() returns a positive number, we are in the parent process
* (the fork return value is the PID of the newly created child process).
* Again we count up to ten.
*/
int i = 0;
for (i = 0; i < 10; i++)
{
printf("parent: %d\n", i);
sleep(1);
}
exit(0);
}
}
现在当我多次编译和运行它时,似乎会出现不可预测的行为...有时会按预期运行,有时会在stdout中包含额外的换行符,有时会省略换行符。以下是输出的示例:
user@HAL10000 ~/c++/sandbox/src
$ gcc fork_and_stuff.c -o fork_and_stuff
user@HAL10000 ~/c++/sandbox/src
$ ./fork_and_stuff.exe
parent: 0child: 0
parent: 1child: 1
parent: 2child: 2
parent: 3child: 3
parent: 4child: 4
parent: 5child: 5
child: 6
parent: 6
child: 7
parent: 7
child: 8
parent: 8
child: 9
parent: 9
user@HAL10000 ~/c++/sandbox/src
$ ./fork_and_stuff.exe
parent: 0
child: 0
parent: 1
child: 1
parent: 2
child: 2
parent: 3
child: 3
parent: 4
child: 4
parent: 5
child: 5
parent: 6
child: 6
parent: 7
child: 7
parent: 8
child: 8
parent: 9
child: 9
user@HAL10000 ~/c++/sandbox/src
$ ./fork_and_stuff.exe
parent: 0child: 0
parent: 1child: 1
parent: 2child: 2
parent: 3child: 3
parent: 4child: 4
child: 5
parent: 5
parent: 6child: 6
parent: 7child: 7
child: 8parent: 8
parent: 9child: 9
这是一些看起来很可怕的输出。我的电脑被鬼附了吗?如果是,是什么东西附在上面了?我该如何驱除它?
fflush(stdout);
并没有改变行为... 即使字符串有一个换行符并且我礼貌地要求它刷新。 - Jimmy