gpt4 book ai didi

c - Sem_post() 无法正常工作,既不会增加信号量的值,也不会解锁附加到该信号量的进程

转载 作者:行者123 更新时间:2023-11-30 14:42:11 25 4
gpt4 key购买 nike

sem_post() 无法正常工作,既不增加信号量的值,也不阻止附加到该信号量 block 队列的进程

#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
sem_t pa,ch;
sem_init(&pa,1,1);
sem_init(&ch,1,0);

pid_t p1;

p1 = fork();
if(p1>0) //Parent process
{
while(1)
{
sem_wait(&pa);
printf("Parent\n");
sem_post(&ch);
}
}
else if(p1==0)
{
while(1)
{
sem_wait(&ch);
printf("child\n");
sem_post(&pa);
}
}
else
printf("\nError\n");

return 0;
}

预期输出是

Parent
child
Parent
child
Parent
child
.. and so on..

实际输出是

Parent

最佳答案

引用man sem_init:

int sem_init(sem_t *sem, int pshared, unsigned int value);

If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory (see shm_open(3), mmap(2), and shmget(2)). (Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.) Any process that can access the shared memory region can operate on the semaphore using sem_post(3), sem_wait(3), and so on.

您的信号量不在共享内存中,因此 fork 的子进程不会看到父进程中所做的任何更改(反之亦然)。因此两个进程都会陷入死锁。

关于c - Sem_post() 无法正常工作,既不会增加信号量的值,也不会解锁附加到该信号量的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54532268/

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