Verifying the relationship between a Linux subprocess and a parent process using code _c language

Source: Internet
Author: User
Tags function definition

Copy Code code as follows:

/******** BASIC.C ********/
#include "basic.h"

pid_t Fork (void)
{
pid_t pid = fork ();
if (PID < 0) {
fprintf (stderr, "Fork Error:%s\n", Strerror (errno));
Exit (0);
}

return PID;
}

Copy Code code as follows:

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>
/* Function definition concerned with BASIC.C * *
pid_t Fork ();

#endif

Copy Code code as follows:

FORK.C *********

#include "basic.h"

int main ()
{
int pid = Fork ();
int x = 2;

if (PID = = 0) {
printf ("Child:pid =%d, Ppid =%d, x =%d\n", Getpid (), Getppid (), ++x);
Sleep (3);

printf ("Child:pid =%d, Ppid =%d, x =%d\n", Getpid (), Getppid (), ++x);
Exit (0);
}

printf ("Parent:pid =%d, Ppid =%d, x =%d\n", Getpid (), Getppid (),--x);

}

Through GCC fork.c basic.c-o Fork Compile-ready fork program. Run./fork

You can see that the parent process exits first, the ppid of the child before exiting is 12256, and the ppid of the subprocess becomes 1. The child process after the parent process exits is adopted by the INIT super Process 1. And the process is not going to quit.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.