second child, parent pid = 1
而我得到的结果是
second child, parent pid = 1996
代码: 全选
#include "apue.h"
#include <sys/wait.h>
int main(void)
{
pid_t pid;
if ((pid = fork()) < 0) { /* first child */
err_sys("fork error");
} else if (pid == 0) {
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid > 0)
exit(0); /* parent from second fork == first child */
/*
* We're the second child; our parent becomes init as soon
* as our real parent calls exit() in the statment above.
* Here's where we'd continue executing, knowing that when
* we're done, init will reap our status.
*/
sleep(2);
printf("second child, parent pid = %ld\n", (long)getppid());
exit(0);
}
if (waitpid(pid, NULL, 0) != pid) /* wait for first child */
err_sys("waitpid error");
/* We're the parent (the original process); we continue executing,
* knowing that we're not parent of the second child.
*/
exit(0);
}
在非main函数调用vfork, 却产生了2个子进程,请问这是为何?(APUE 习题8.2)
代码: 全选
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
static void f1(void), f2(void);
int main(void) {
f1();
f2();
_exit(0);
}
static void f1() {
pid_t pid;
if ((pid = vfork()) < 0) {
printf("vfork error.\n");
_exit(-1);
}
printf("pid : %ld, getpid() : %ld, getppid() : %ld.\n",
(long)pid, (long)getpid(), (long)getppid());
}
static void f2() {
char buf[1000] ;
int i;
for (i = 0; i<sizeof(buf); i++)
buf[i] = 0;
}
/**
输出:
pid : 0, getpid() : 7720, getppid() : 7719.
pid : 7720, getpid() : 7719, getppid() : 4364.
pid : 0, getpid() : 7721, getppid() : 7719.
Segmentation fault
*/
刚学习APUE没多久,很多困惑,希望大家给小弟解惑。
谢谢大家。