[国嵌攻略][084][信号同步编程]

进程同步

一组并发进程进行相互合作、相互等待,使得各进程按一定的顺序执行的过程称为进程间的同步。

进程同步与进程互斥

进程同步问题的关键在于生产者不需要获取信号量,消费者不需要释放信号量,所以信号量的初值设置为0。但是进程互斥问题中双方都需要获取和释放信号量,所以信号量的初值至少为1。

producor.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/ipc.h>
#include <sys/sem.h>

void main(){
    //创建文件
    int fd;
    
    fd = open("product.txt", O_RDWR | O_CREAT, 0777);
    
    //睡眠等待
    sleep(10);
    
    //写入数据
    write(fd, "The product is finished!", 25);
    
    //关闭文件
    close(fd);
    
    //创建信号量
    int key;
    int semid;
    
    key = ftok("product.txt", 0);
    semid = semget(key, 1, IPC_CREAT);
    
    //设置信号量
    semctl(semid, 0, SETVAL, 0);   //设置信号量0的值为0
    
    //释放信号量
    struct sembuf sops;
    
    sops.sem_num = 0;
    sops.sem_op = 1;
    sops.sem_flg = SEM_UNDO;
    
    semop(semid, &sops, 1);
}

customer.c

#include <stdlib.h>

#include <sys/ipc.h>
#include <sys/sem.h>

void main(){
    //打开信号量
    int key;
    int semid;
    
    key = ftok("product.txt", 0);
    semid = semget(key, 1, IPC_CREAT);
    
    //获取信号量
    struct sembuf sops;
    
    sops.sem_num = 0;
    sops.sem_op = -1;
    sops.sem_flg = SEM_UNDO;
    
    semop(semid, &sops, 1);
    
    //拷贝文件
    system("cp product.txt ship.txt");
}
原文地址:https://www.cnblogs.com/d442130165/p/5225409.html