c++之linuxIPC(四)--有名信号量(posix)

#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>


int main(int argc,char**argv)
{
    int index=0;
    sem_t *sem_cf=NULL;
    sem_t *sem_fs=NULL;
    sem_t *sem_sc=NULL;

    sem_cf=sem_open("sem_cf",O_CREAT|O_RDWR,0777,0);
    sem_post(sem_cf);

    int nret=fork();
    if(nret==0)
    {
        nret=fork();
        if(nret==0)
        {
            sem_cf=sem_open("sem_cf",O_CREAT|O_RDWR,0777,0);
            sem_sc=sem_open("sem_sc",O_CREAT|O_RDWR,0777,0);
            while(1)
            {
                sem_wait(sem_sc);
                printf("child process,index:%d\n",index++);
                usleep(50);
                sem_post(sem_cf);
                if(index>10)break;
            }
        }else if(nret>0)
        {
            sem_cf=sem_open("sem_cf",O_CREAT|O_RDWR,0777,0);
            sem_fs=sem_open("sem_fs",O_CREAT|O_RDWR,0777,0);

            while(1)
            {
                sem_wait(sem_cf);
                printf("father process,index:%d\n",index++);
                usleep(50);
                sem_post(sem_fs);
                if(index>10)break;
            }

        }
    }else if(nret>0)
    {
        sem_t *sem_fs=sem_open("sem_fs",O_CREAT|O_RDWR,0777,0);
        sem_t *sem_sc=sem_open("sem_sc",O_CREAT|O_RDWR,0777,0);
        while(1)
        {
            sem_wait(sem_fs);
            printf("sun process,index:%d\n",index++);
            usleep(50);
            sem_post(sem_sc);
            if(index>10)break;
        }
    }



    return 0;
}
father process,index:0
father process,index:1
sun process,index:0
sun process,index:1
child process,index:0
child process,index:1
father process,index:2
sun process,index:2
father process,index:3
child process,index:2
sun process,index:3
father process,index:4
child process,index:3
sun process,index:4
father process,index:5
child process,index:4
sun process,index:5
father process,index:6
child process,index:5
sun process,index:6
father process,index:7
child process,index:6
sun process,index:7
child process,index:7
father process,index:8
sun process,index:8
father process,index:9
sun process,index:9
child process,index:8
child process,index:9
father process,index:10
sun process,index:10
child process,index:10
按 <RETURN> 来关闭窗口...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值