Process (Linux) (C)

  • program:

ordered set of instructions

static

  • process:

One-time execution of a program, including creation, execution, and termination

It is the smallest unit for the system to allocate resources

  • The composition of the process:

  • text paragraph

A code segment from a program, an instruction

  • user data segment

The data segment from the program, .data (global variables, constants) .bass (uninitialized global variables)

  • system data segment

Stack (stack space data) local variables, formal parameters, function return value

register

PCB process control block

  • process id

  • priority

  • process user

  • Classification of processes:

  • interactive process

Foreground process (a process that can be input or output by the terminal)

Background process (can only output to the terminal)

  • batch process

Does not belong to a terminal, just submits the process to a queue for sequential execution

  • daemon process

A process that starts running when the operating system starts up and terminates when the operating system shuts down

  • Status of the process:

  • running state

Running state: with cpu

Ready state: ready to run

  • wait state

Interruptible: There are resources to return to the running state

Uninterruptible: resources do not necessarily return to the running state, special conditions are required

  • stop state

Suspended in background (foreground ctrl+z to stop)

  • Zombie state

The process ends and its resources have not been reclaimed

  • death state

Process complete

  • Process scheduling:

  • PS:

ps -aus: view process details

stat: process status

S: waiting state

s: the process that has child processes

I (uppercase i): process idle in the kernel

N: low priority process

<: high priority process

l (lowercase L): process with child threads

+ : process running in the foreground

R: running state

T: stop state

Z: Zombie state

  • top:

NI: priority (-20 – 19, high – low)

nice:

-n 5 ./a.out (run at priority 5 when running)

renice:

-n 10 PID (modify this process priority)

  • kill: send a signal to the specified process

-l: View all signals (62 in total)

-9: Kill the process

-19: suspend process

  • bg: run the stopped state to the background

+ task number

+ %PID

  • fg: Bring the stopped state to the foreground

+ task number

+ %PID

  • The mode of the process (execution mode):

user mode

kernel mode

  • Process-related system calls:

#include

pid_t fork(void);

Function: create subprocess

Return value: return the PID of the child process to the parent process successfully, return 0 to the child process, and return -1 to the parent process on failure

The child process will copy almost all the content of the parent process

The difference between parent and child processes running:

The parent process starts running from main

The child process starts running from fork (the current state of the parent node)

Parent and child processes participate in unified scheduling, and the running order is not necessarily

Generally speaking, the parent process reclaims resources when the child process ends.

If the parent process ends first, the resources of the child process are reclaimed by other processes

#include

#include

pid_t vfork(void);

Function: create subprocess

Return value: return the PID of the child process to the parent process successfully, return 0 to the child process, and return -1 to the parent process on failure

The difference: the parent process starts to execute after the vfork child process ends, and the fork sequence is not necessarily

#include

pid_t getpid(void);//Get the current process PID

pid_t getppid(void);//Get the parent process PID

exec function family (process content replacement, run other executable files, PID will not change)

#include

extern char **environ;

int execl(const char *pathname, const char *arg, …/* (char *) NULL */);

int execlp(const char *file, const char *arg, …/* (char *) NULL */);

int execle(const char *pathname, const char *arg, … /*, (char *) NULL, char *const envp[] */);

int execv(const char *pathname, char *const argv[]);

int execvp(const char *file, char *const argv[]);

int execvpe(const char *file, char *const argv[], char *const envp[]);

pathname: path name

file: file name (execlp and execvp use the system environment variable as the running address, and the executable file needs to be in the bin)

arg: command and its arguments (“command”, “arguments”)

NULL: end

envp: An array of pointers to store environment variables

l: in the form of a list

v: in the form of a container

Run error returns -1

#include

void exit(int status);

Function: the current process exits

status: The status value when the process exits, 0 means normal end

#include

void _exit(int status);

Function: the current process exits

status: The status value when the process exits, 0 means normal end

Difference: standard library calls and system calls

_exit does not flush the buffer content when the process ends, while exit flushes the buffer

#include

#include

pid_t wait(int *wstatus);

Function: The process blocks and waits for the child process to end

Return value: successfully returns the PID of the exiting child process, fails to return -1

wstatus: Get the status value of the child process exit

Macro function to view process exit status value

WEXITSTATUS(wstatus)//equivalent ((wstatus >> 8) & amp; 0xff, returns the value in the subprocess exit)

Check if the process exited normally

WIFEXITED(wstatus)//equivalent (wstatus & amp; 0x7f, if it exits normally, it is 0; if it exits abnormally, it returns the corresponding abnormal signal)

pid_t waitpid(pid_t pid, int *wstatus, int options);

Function: Handle subprocess

Return value: If the option is 0 successfully, return the pid of the exiting child process; if the option is WNOHANG, return 0 if there is no child process, and return the PID if there is one. Return -1 on failure

pid: >0 waits for the specified process pid, -1 waits for any child process to exit, <-1 waits for any child process whose group ID is equal to the absolute value of pid, 0 waits for any child process whose group ID is equal to pid

wstatus: Get the status value of the child process exit

option: 0: block waiting for the process to end, WNOHANG: non-blocking processing sub-process exit (if no sub-process exits, it will return immediately, if the sub-process exits, process resources)

  • daemon process

The process that starts running when the Linux system starts and ends when the system is shut down. The actual work is to complete certain specific operations periodically

Daemo daemon process: does not belong to a certain terminal, but also a background jinc

  1. Create a child process, end the parent process, and the child process will become a background process

  1. Get rid of the terminal, create a new session group, and make the child process the leader of the session group

#include

#include

pid_t setsid(void);

Return value: sid session number for success, -1 for failure

  1. Change the working directory of the process, it is recommended to change to the root directory

#include

int chdir(const char *path);

path: folder path

Return value: 0 for success, -1 for failure

  1. reset file mask

#include

#include

mode_t umask(mode_t mask);

mask: the reset mask value

  1. close all open file descriptors

#include

int getdtablesize(void);

Return value: the maximum value of the current file descriptor

  1. Daemon related functions

define by yourself

  • Some code examples

//fork to create a process
#include <stdio.h>
#include <unistd.h>
void fun01()
{
    while(1)
    {
        printf("child process\\
");
        sleep(1);
    }
}
void fun02()
{
    while(1)
    {
        printf("parent process\\
");
        sleep(1);
    }
}
int main(int argc, char *argv[])
{
    int pid = fork();
    if(pid<0)
    {
        perror("fork");
        return -1;
    }
    if(pid==0)
    {
        fun01();
    }else
    {
        fun02();
    }
    return 0;
} 
//exec
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
    printf("Run:\\
");
    execl("/bin/ls","ls","-l",NULL);

    /*char *a[]={"ls",NULL};
    execv("/bin/ls",a);*/
    return 0;
} 
//wait
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    pid_t pid = fork();
    if(pid==0)
    {
        printf("Im child pid=%d\\
",getpid());
        sleep(1);
        exit(10);
    }
    else
    {
        int status;
        int cpid=wait( & amp;status);
        printf("Im parent cpid=%d status=%d\\
",cpid,WEXITSTATUS(status));
    }
    return 0;
}
//waitpid
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    pid_t pid = fork();
    if(pid==0)
    {
        sleep(1);
        printf("Im child\\
");
        exit(10);
    }
    else
    {
        int status;
        int cpid=waitpid(-1, & amp;status,0);
        printf("Im parent cpid=%d status=%d",cpid,WEXITSTATUS(status));
    }
    return 0;
}
//Create a daemon process
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    //Create a child process and make it a background process
    pid_t pid = fork();
    if(-1 == pid)
    {
        perror("fork is fail");
        exit(-1);
    }
    else if(0 == pid)
    {
        //Create a conversation group and become the leader of the conversation group
        pid_t sid = setsid();
        if(-1 == sid)
        {
            perror("sid is fail");
            exit(-1);
        }
        // modify the working directory
        int ret = chdir("/");
        if(-1 == ret)
        {
            perror("chdir is fail");
            exit(-1);
        }
        // modify the file mask
        umask(0);
        //Close all open file descriptors
        int num = getdtablesize();
        for(int i = 0;i<num;i++)
        {
            close(i);
        }
        // daemon function
        FILE *fp = fopen("/home/hqyj/zz/process/1.txt","r + ");
        while(1)
        {
            sleep(1);
            time_t m_time = time(NULL);
            struct tm *p = localtime( &m_time);
            char buf[1024]={0};
            sprintf(buf,"%d/%d/%d %d:%d:%d\\
",p->tm_year + 1900,p->tm_mon + 1,p->tm_mday,p-> tm_hour, p->tm_min, p->tm_sec);
            fwrite(buf, sizeof(buf), 1, fp);
        }
    }
}

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge