gpt4 book ai didi

linux - 具有过程的二进制信号量的通用模板

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:42 24 4
gpt4 key购买 nike

我正在学习信号量,想在我以前实现的共享内存程序上试用信号量ipc。(该程序涉及在父进程和子进程之间共享共享内存:读写等)。当我使用一个变量并在父变量中增加它,在子变量中减少它时,由于竞争条件,我得到了意外的输出。所以我想用信号量来同步两者。但我需要一个起点,一个模板开始。
我使用这样的模板(初始化、附加、分离等)完成了前面的共享内存示例。如果有人能提出一些建议…
我想说的是:

struct shmarea    // My shared Memory
{
` unsigned long count;
};
struct shmarea *shma;

main()
{
id = shmget(KEY1,4096,IPC_CREAT|0600);
shma = shmat(id,0,0);
shma->count = 0;
ret = fork();

if(ret>0)
{
printf("in parent .. ppid is %lu ...and pid is %lu\n",getppid(),getpid());
sleep(5);
while(j++ < 2147483645){ // The large loop is to See the processes in top command
while(i++ < 2147483645) shma->count++;
}

}
if(ret==0)
{
printf("in child .. ppid is %lu ...and pid is %lu\n",getppid(),getpid());
while(j++ < 2147483645){
while(i++ < 2147483645) shma->count--;
}
exit(0);
}

if(ret>0)
{
//Clean up
}
}

我确实在寻找信号量创建的例子..但是我大部分时间都在使用信号量集..如何用二进制信号量映射它…因为在这个简单的程序中,我只需要有两个值0和1。

最佳答案

关于linux - 具有过程的二进制信号量的通用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22885600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com