--Personal memo --Leave what you learned about kernel process generation --Run in C
--When you execute the fork () function, it spawns a child process from the parent process.
fork.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
static void child()
{
printf("Child. pid: %d.\n", getpid());
exit(EXIT_SUCCESS);
}
static void parent(pid_t pid_child)
{
printf("Parent. parent's pid: %d. child's pid: %d\n", getpid(), pid_child);
exit(EXIT_SUCCESS);
}
int main()
{
pid_t pid;
pid = fork();
if(pid == -1) err(EXIT_FAILURE, "fork() failed");
//Child process returns 0
if(pid == 0)
child();
//The process ID of the child process whose return value is the parent process(> 0)
else
parent(pid);
}
Parent. parent's pid: 27701. child's pid: 27702
Child. pid: 27702.
You can see that the child process is spawned from the parent process and each has a different process ID
--The kernel executes the process according to the following flow
execve.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
static void child()
{
char *args[] = {"/bin/echo", "Hello", NULL};
printf("child. child's pid: %d.\n", getpid());
execve("/bin/echo", args, NULL);
err(EXIT_FAILURE, "execve() failed");
}
static void parent(pid_t pid_child)
{
printf("parent. parent's pid: %d. child's pid: %d\n", getpid(), pid_child);
exit(EXIT_SUCCESS);
}
int main(void)
{
pid_t pid;
pid = fork();
if(pid == -1)
err(EXIT_FAILURE, "fork() failed");
if(pid == 0)
child();
else
parent(pid);
}
parent. parent's pid: 28034. child's pid: 28035
child. child's pid: 28035.
Hello
After the process branches with the fork () function, you can see that / bin / echo is executed by the execve () function in the child process.
Recommended Posts