OS Programming Lab: Creating Processes

发表于 2021-05-31 14:41 359 字 2 min read

cos avatar

cos

FE / ACG / 手工 / 深色模式强迫症 / INFP / 兴趣广泛养两只猫的老宅女 / remote

该实验通过使用系统调用fork()创建父进程和两个子进程,演示了进程的创建与并发执行。每个进程分别输出字符'a'、'b'和'c',验证了多进程环境下进程的独立性与并发性。

This article has been machine-translated from Chinese. The translation may contain inaccuracies or awkward phrasing. If in doubt, please refer to the original Chinese version.

I. Experiment Objective

Familiarize with the use of operating system program interfaces. You need to have a virtual machine set up; here we use deepin.

II. Experiment Content

Write a program that uses the system call fork() to create two child processes. When this program runs, there will be one parent process and two child processes active in the system. Let each process display a character on the screen: the parent process displays ‘a’, and the child processes display ‘b’ and ‘c’ respectively.

III. Experiment Code

unistd.h is a built-in header file in Linux/Unix systems that contains function prototypes for many system services, such as read, write, and getpid functions. Its role is equivalent to “windows.h” in Windows operating systems — it provides a unified API interface for users to conveniently call system services.

When the fork function is called in the current process, it creates a child process and returns the child process’s pid. In the child process, fork returns 0. Therefore, the test code can be written as follows:

#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
    pid_t pid = 5;
    int flag = 1;
    pid = fork();
    if(pid < 0)
        cout << "Error in fork!" << endl;
    else if (pid == 0) cout << "I am Child1!Pid is " << pid << ". content:b" << endl;
    else {
        cout << "I am Parent!Pid is " << pid << ". content:a" << endl;
        pid_t pid2 = fork();
        if (pid2 == 0) cout << "I am Child2!Pid is " << pid2 << ". content:c" << endl;
    }
    cout << "over." << endl;
    return 0;
}

IV. Runtime Result Screenshots

First run

Insert image description here

Second run

Insert image description here

As we can see, the three processes execute independently of each other, and the results exhibit non-reproducibility.

After adding an I/O blocking line, opening the task manager to check process IDs confirms that there are indeed three processes running.

Insert image description here

喜欢的话,留下你的评论吧~

© 2020 - 2026 cos @cosine
Powered by theme astro-koharu · Inspired by Shoka