大家好我想问一个关于 fork 的问题
这是代码
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#define MAX_COUNT 5
#define BUF_SIZE 100
void main(void)
{
pid_t pid;
int i;
char buf[BUF_SIZE];
fork();
pid = getpid();
for (i = 1; i <= MAX_COUNT; i++) {
sprintf(buf, "This line is from pid %d, value = %d\n", pid, i);
write(1, buf, strlen(buf));
}
printf("child id :%d\n" , pid);
printf("parent id :%d\n" , getppid());
}
当我运行它时这里是输出
This line is from pid 31130, value = 1
This line is from pid 31130, value = 2
This line is from pid 31130, value = 3
This line is from pid 31130, value = 4
This line is from pid 31130, value = 5
child id :31130
This line is from pid 31131, value = 1
parent id :31052
This line is from pid 31131, value = 2
This line is from pid 31131, value = 3
This line is from pid 31131, value = 4
This line is from pid 31131, value = 5
child id :31131
parent id:31130
这让我很困惑,为什么
打印两次parent id和child id的行
为什么我调用时两次的 child ID 值都不同 只有一次
为什么第二次父id值等于第一个子id值
实际上什么是父 ID 和智利 ID 非常感谢
最佳答案
fork
函数被调用一次,返回两次。所以 child 和 parent 都执行 printf
。
printf("child id :%d\n" , pid); /* Both child and parent print this. */
printf("parent id :%d\n" , getppid()); /* Both child and parent print this. */
您说“ child ”和“ parent ”这一事实并没有真正改变任何东西,所以这就是您得到误导性结果的原因。
一个常见的模式是测试 fork
返回的值。它在子节点中返回 0
,在父节点中返回子节点的 PID。
pid_t pid = fork();
if (pid)
printf("I am the parent, pid: %d. The child has pid: %d\n", getpid(), pid);
else
printf("I am the child, pid: %d\n", getpid());
/* Common code. */
for...
关于c - fork 过程的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7750710/