C language process (Chapter 1 process basics, fork() function, pid_t, pid, getpid())

C language process (Chapter 1 process basics, fork() function, pid_t, pid, getpid())

Introduction

When we use c programming to build an application, we often encounter such a scenario: we need to complete several tasks in the program at the same time, such as processing data, printing output, and reading user input. This need to perform multiple tasks at the same time with higher efficiency is called "concurrency".

Generally, the operating system is responsible for coordinating and allocating computer resources, and managing "processes" and "threads". In C language, we can use processes and threads to achieve concurrent execution.

  • A process is a resource managed by the operating system, which is the running space and memory address that needs to be accessed and controlled when the program is running. Each process has its own memory space, system resources, open files, interaction with other processes, and so on.

We often treat the entire program as a process, but a program may contain multiple running instances at the same time, that is, multiple processes. For example, many tasks such as browsing web pages, downloading files, and playing videos are performed in a browser at the same time, and these tasks will be performed in different processes.

getting Started

Related online editing website: https://www.ideone.com/whPQYr

After learning the concepts of processes and threads, the following are some C language cases suitable for getting started:

  1. Create a simple process
#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h> 

int main() {
    
    
    pid_t pid;
    pid = fork();

    if (pid == -1) {
    
    
        printf("error: 创建进程失败 \n");
        exit(1);
    } else if (pid == 0) {
    
    
        printf("我是子进程,我的pid是 %d \n", getpid());
    } else {
    
    
        printf("我是父进程,我的pid是 %d \n", getpid());
    }

    return 0;
}

The program uses the fork() function to create new processes. If the pid value is less than 0, the fork() system call fails and creating a new process cannot be completed; if the pid is equal to 0, it means that the currently running process is a child process. So we can get the process id of the parent process and the process id of the child process by executing this program.

Running result :
insert image description here
Running result explanation:
The output of this program running is:

我是父进程,我的pid是 3173 
我是子进程,我的pid是 3213 

When the program is running, when the fork() function is called, the process will generate a new address space, and then copy the data of the parent process to the new address space. The new process is the so-called child process, which is almost identical to the parent process except for the process ID.

  • In the parent process, the fork() function returns the process ID number of the child process, that is, the variable pidvalue is greater than 0. If the pid is equal to -1, it means that the process creation failed.
  • In the child process, the fork() function returns 0, so it is executed else if (pid == 0)in
    to output the format string of "I am a child process, and my pid is xxx", and use getpid() to obtain the PID number of the child process.
  • In the parent process, execute in elsethe statement block, print "I am the parent process, and my pid is xxx". Use getpid() to get the parent process's own PID number.

The order in which the two print messages appear is indeterminate, depending on which process the operating system chooses to run on, which may vary on each computer and each operating system.

fork()

fork()A function is a function that creates a new process in the Unix operating system. In C language, you can use this function to create a new process.

Specifically, when the program executes to fork()the function , it will create a child process and make it run the same code, which is equivalent to "copying" the original process to form two almost identical processes. Among them, the original process is called the parent process, and the newly created process is called the child process. In the parent process and the child process, different processes are distinguished by the return value of the fork() function, because in the child process, the fork() function will return 0, and in the parent process, the value will be the child process it created The process ID.

fork()Functions can be used to fork common processes, and execve()a series to load different commands.

Here is a basic fork()function use case:

#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h> 

int main() {
    
    
    pid_t pid;
    pid = fork();

    if (pid == -1) {
    
    
        printf("error: 创建进程失败 \n");
        exit(1);
    } else if (pid == 0) {
    
    
        printf("我是子进程,我的pid是 %d \n", getpid());
    } else {
    
    
        printf("我是父进程,我的pid是 %d \n", getpid());
    }

    return 0;
}

In this example, calling the fork() function creates a child process. If the fork() function call fails, it will return -1; in the child process, its return value is 0, and in the parent process, its return value is the child process ID.

It should be noted that the fork() function is very resource-intensive, because the function needs to copy the entire process. Therefore, you should try to avoid using more than necessary fork() function calls in the code, and optimize it in terms of reducing system resource consumption and time delay when it is used multiple times.

operation result:
insert image description here

pid

pid is an abbreviation for "process ID", the process ID.

In an operating system, each running process is assigned a unique integer process ID (PID), which identifies the process. The process ID plays a very important role in the system for identifying processes, managing process status, etc., which means that a unique PID means a corresponding unique process identifier. On Linux and Unix systems, you can use psthe command and other system tools to view currently running processes and their PIDs.

You can get the pid of the current process by writing a shell script or a C language program, using the getpid() function, as follows:

#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h> 

int main() {
    
    
    printf("当前进程的pid是:%d\n", getpid());
    return 0;
}

In this program, use the getpid() function to get the PID of the current process and print it out. Because the PID of each process is unique, when you run this program, you will get a unique PID value output that is different from other running processes.

In summary, understanding and using process IDs in an operating system is important to aid developers and system administrators in various monitoring and management activities, as well as in better debugging and error handling.

Running result :
insert image description here

pid_t

In C language, pid_tit is an integer type used to represent the ID of the process. Specifically, on most Unix or Linux systems, pid_tis defined as follows:

typedef int pid_t;

Therefore, pid_tit is actually intof type and is generally intequal in size to .

pid_tThis type is used to make the code more portable. Because the implementation of the process ID may be different between different platforms, for example, the Windows platform uses the HANDLE type instead of pid_t; the maximum value of the PID may also be different on the 32-bit system and the 64-bit system, and using this type can guarantee The program can compile and run normally on different platforms. Therefore, when writing programs that depend on process IDs, it is better to use pid_tthan hard-coded integer types.

<unistd.h>In the C standard library , fork()the function description returns a value of pid_ttype , so as to conveniently obtain the PID number of the newly created process, the sample code is as follows:

#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h> 

int main() {
    
    
    pid_t pid;
    pid = fork();

    if (pid == -1) {
    
    
        printf("error: 创建进程失败 \n");
        exit(1);
    } else if (pid == 0) {
    
    
        printf("我是子进程,我的pid是 %d \n", getpid());
    } else {
    
    
        printf("我是父进程,我的pid是 %d \n", getpid());
    }

    return 0;
}

In this program, define pid_t pidto save the process ID value, which is the return value of the fork function. This helps make your code more C-compliant and use operating system-provided functionality in a portable manner.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/130529969