我对 C 完全陌生,并且正在学习流程。我对下面的代码实际上在做什么有点困惑,它取自 Wikipedia,但我在几本书中看到了它,并且不确定为什么,例如,我们这样做了pid_t pid;
then pid = fork();
。我的阅读似乎表明子进程返回 a pid
of ,但是,我认为非常原始的父进程在看到根为 的树后0
会保持pid
of 。0
pid 0
例如,pid = fork();
对父母做了什么?因为它不为孩子做同样的事情吗?并且不会pid = fork();
将其放入循环中,因为它会为每个孩子执行此操作?
基本上,有人可以向我解释每一步,就好像我是五岁一样?也许更年轻?谢谢!
#include <stdio.h> /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#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)
{
/* Error:
* When fork() returns -1, an error happened
* (for example, number of processes reached the limit).
*/
fprintf(stderr, "can't fork, error %d\n", errno);
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
/* Child process:
* When fork() returns 0, we are in
* the child process.
*/
int j;
for (j = 0; j < 10; j++)
{
printf("child: %d\n", j);
sleep(1);
}
_exit(0); /* Note that we do not use exit() */
}
else
{
/* 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;
for (i = 0; i < 10; i++)
{
printf("parent: %d\n", i);
sleep(1);
}
exit(0);
}
return 0;
}