Operating system exercises: Create processes on Linux and view process status

illustrate

A process can create multiple new processes during execution. The created process is called the "parent process" and the new process is called the "child process". Each new process can create other processes, forming a process tree.

Each process has a unique process identifier (pid). In Linux, the init process is the root process for all other processes.

In Linux, a new process can be created through the system call fork(), and the address space of the new process copies the address space of the original process. Both the parent process and the child process will continue to execute the instructions after the fork() call.

Note: This article is an exercise in Chapter 3 of "Operating System Concepts (Ninth Edition)".

Create process

C code example to create a process

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(){
    
    
        pid_t pid;

        pid = fork();

        /* Both parent and child process will continue from here */
        printf("current pid: %d \n", getpid());

        if (pid < 0){
    
    
                /* error occurred */
                fprintf(stderr, "Fork Failed");
                return 1;
        } else if (pid == 0) {
    
    
                /* child process */
                printf("In Child, pid: %d, ppid: %d\n", getpid(), getppid());
                execlp("/bin/ls", "ls", NULL);
        } else {
    
    
                /* parent process will wait for the child process to complete */

                /* 如果子进程已经结束了,但是其父进程还没有调用wait(),这个进程就是僵尸进程 */
                sleep(20);

                wait(NULL);
                printf("In parent, pid: %d, ppid: %d\n", getpid(), getppid());
        }

        return 0;
}

file

Compile and execute

  • Compile:gcc -o process process.c
  • implement:./process
  • The output of the execution result is as follows:
current pid: 198495									#父进程执行的,获取到的是父进程的pid
current pid: 198496									#子进程执行的,获取到的是子进程的pid
In Child, pid: 198496, ppid: 198495			 #在子进程的判断语句中,pid为子进程pid,ppid为父进程的pid
process  process.c									 #在子进程的判断语句中,执行execlp("/bin/ls", "ls", NULL);的输出。在此之后的20秒,子进程执行结束,短暂变为僵尸进程
In parent, pid: 198495, ppid: 197721		#在父进程的判断语句中,pid为父进程的pid,ppid为父进程的父进程pid

View progress

  • ps -ef: Lists complete information about all currently active processes in the system
    file

  • ps -l: You can view the process status, the status column is in column S; the process with status Z is a zombie process
    file

  • pstree: Display the process in a tree structure
    file

Guess you like

Origin blog.csdn.net/weixin_42534940/article/details/132394347