操作系统导论

Hello World

  1. 安装gcc用来编译c代码
bash 复制代码
sudo yum install gcc
  1. 编写Hello World
c 复制代码
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
  1. 使用gcc编译
    -o 是指定出处文件的名字------也就是编译完的文件会叫hello
bash 复制代码
gcc hello.c -o hello
  1. 运行
    ./hello运行

开篇

虚拟化CPU

  1. 编写一段代码,效果为反复打印用户启动程序时传入的字符串
    vim cpu.c
c 复制代码
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
void spin(int seconds){
        usleep(seconds *1000000);
}
int main(int argc,char *argv[]) {
    if(argc!=2){
        fprintf(stderr,"usage:cpu<string>\n");
        exit(1);
    }
    char* str=argv[1];
    while(1){
        spin(1);
        printf("%s\n",str);
    }

    return 0;
}
  1. 编译
    gcc -o cpu cpu.c
  2. 启动一个
    ./cpu A
  3. 同时启动多个
    ./cpu A & ./cpu B & ./cpu C & ./cpu D
  4. 终止运行
    killall cpu

虚拟化内存

并发

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> // 确保包含pthread库的头文件

volatile int counter = 0; // 共享计数器,使用volatile以防止编译器优化
int loops; // 每个线程要执行的循环次数

// 工作线程的函数
void *worker(void *arg) {
    int i;
    for (i = 0; i < loops; i++) {
        counter++; // 增加共享计数器
    }
    return NULL;
}

int main(int argc, char *argv[]) {
    if (argc != 2) { // 检查命令行参数
        fprintf(stderr, "usage: threads <value>\n");
        exit(1);
    }

    loops = atoi(argv[1]); // 从命令行参数获取循环次数
    pthread_t p1, p2; // 创建两个线程标识符

    printf("Initial value : %d\n", counter); // 打印初始计数器值

    // 创建两个线程
    pthread_create(&p1, NULL, worker, NULL); 
    pthread_create(&p2, NULL, worker, NULL); 

    // 等待两个线程完成
    pthread_join(p1, NULL); 
    pthread_join(p2, NULL); 

    printf("Final value : %d\n", counter); // 打印最终计数器值
    return 0;
}

加互斥锁

c 复制代码
#include <pthread.h>

pthread_mutex_t lock; // 声明一个互斥锁

void *worker(void *arg) {
    int i;
    for (i = 0; i < loops; i++) {
        pthread_mutex_lock(&lock); // 加锁
        counter++;
        pthread_mutex_unlock(&lock); // 解锁
    }
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_mutex_init(&lock, NULL); // 初始化互斥锁
    ...
    pthread_mutex_destroy(&lock); // 销毁互斥锁
}

持久化

相关推荐
明月看潮生16 小时前
青少年编程与数学 01-011 系统软件简介 02 UNIX操作系统
服务器·青少年编程·操作系统·unix·系统软件
明月看潮生16 小时前
青少年编程与数学 01-011 系统软件简介 05 macOS操作系统
macos·青少年编程·操作系统·系统软件·编程与数学
Lumos_1 天前
OpenEluer 安装 OpenLDAP
操作系统
GoGeekBaird2 天前
69天探索操作系统-第69天:高级进程调度:实时和基于优先级的任务管理技术
后端·操作系统
GoGeekBaird2 天前
69天探索操作系统-第68天:从用户到内核:实现动态系统调用处理以构建健壮的操作系统
后端·操作系统
免檒2 天前
第二章 进程管理
算法·操作系统
egoist20233 天前
【Linux仓库】冯诺依曼体系结构与操作系统【进程·壹】
linux·运维·服务器·开发语言·操作系统·冯诺依曼体系结构
望获linux3 天前
【Linux基础知识系列】第八篇-基本网络配置
linux·数据库·postgresql·操作系统·php·开源软件·rtos
GoGeekBaird3 天前
69天探索操作系统-第67天:从恐慌到解决:实施内核调试技术进行崩溃分析
后端·操作系统
shark-chili3 天前
Java并发编程哲学系列汇总
linux·运维·服务器·操作系统