IPC之System V 信号量(后续代码实现)

本文介绍了一个简单的信号量代码实现,包括信号量的创建、初始化、进程间通信和信号量操作。通过Fork创建子进程并利用信号量进行资源管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上篇概括了system V信号量基本使用,下面自己实现的一个简单的信号量代码:

#include <sys/sem.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>


union semun {
	int val;
	struct semid_ds *buf;
	short *array;
};

void child1(int semid);
void child2(int semid);

int main()
{ 
    int ret;
    pid_t pid1,pid2;
    int semid1,semid2;
    struct sembuf sem;
    union semun sem_val;

    if((semid1 = semget(IPC_PRIVATE,1,IPC_CREAT|0666)) < 0){
	 perror("semget semid1 error!\n");
    }
    if((semid2 = semget(IPC_PRIVATE,1,IPC_CREAT|0666)) < 0){
	perror("semget semid2 erroe!\n");
    }

    sem_val.val = 0;

    ret = semctl(semid1,0,SETVAL,sem_val);
    if(ret < 0){
	perror("semctl1 error!\n");
    }

    ret = semctl(semid2,0,SETVAL,sem_val);
    if(ret < 0){
	perror("semctl2 error!\n");
    }

    pid1 = fork();
    if(pid1 < 0){
	perror("fork pid1 error\n");
    }
    else if(pid1 == 0){
	child1(semid1);
    }

    pid2 = fork();
    if(pid2 < 0){
	perror("fork pid2 error\n");
    }
    else if(pid2 == 0){
	child2(semid2);
    }
    
    sem.sem_num = 0;
    sem.sem_op  = 1;
    sem.sem_flg = SEM_UNDO;

    while(1)
    {
	sleep(1);
	if(semop(semid1,&sem,1) == -1){
	    perror("semop semid1\n");
	}
	if(semop(semid2,&sem,1) == -1){
	    perror("semop semid2\n");
	}
    }
	
    return 0;
}

void child1(int semid1)
{
    struct sembuf sem1;

    sem1.sem_num = 0;
    sem1.sem_op  = -1;
    sem1.sem_flg = SEM_UNDO;

    while(1)
    {
	if(semop(semid1,&sem1,1) == -1){
	    perror("semop semid1\n");
	}
	printf("this is the child1\n");
	sleep(1);
    }
}

void child2(int semid2)
{
    struct sembuf sem2;

    sem2.sem_num = 0;
    sem2.sem_op  = -5;
    sem2.sem_flg = SEM_UNDO;

    while(1)
    {
	if(semop(semid2,&sem2,1) == -1){
	    perror("semop semid2\n");
	}
	printf("this is the child2\n");
	sleep(1);
    }
}













运行结果如下:
this is the child1
this is the child1
this is the child1
this is the child1
this is the child1
this is the child2
this is the child1
this is the child1
this is the child1
this is the child1
this is the child1
this is the child2

本文仅限学习之用,如有雷同不胜荣幸!!有误之处请指出,谢谢合作!




















评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值