Use code to verify the relationship between a Linux child and its parent
- 2020-04-02 02:13:26
- OfStack
#include "basic.h"
pid_t Fork(void)
{
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork error: %sn", strerror(errno));
exit(0);
}
return pid;
}
********** basic.h ***********
#ifndef __CSAPP_BASIC_H
#define __CSAPP_BASIC_H
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
pid_t Fork();
#endif
******* fork.c *********
#include "basic.h"
int main()
{
int pid = Fork();
int x = 2;
if (pid == 0) {
printf("child: pid = %d, ppid = %d, x = %dn", getpid(), getppid(), ++x);
sleep(3);
printf("child: pid = %d, ppid = %d, x = %dn", getpid(), getppid(), ++x);
exit(0);
}
printf("parent: pid = %d, ppid = %d, x = %dn", getpid(), getppid(), --x);
}
through gcc fork.c basic.c -o fork compilable fork The program. run ./fork
You can see that the parent process exits first, before exiting child the PPID for 12256 . Of the post-exit child process PPID Into the 1. Explains the parent process exit by the child process init Super process 1 Adoption. And the process is never going away.