父进程和子进程之间的 POSIX 信号量
POSIX semaphores between parent and child process
我希望从父进程和子进程交替输出以下输出
parent : 2 x 1 = 2
child : 2 x 2 = 4
parent : 2 x 3 = 6
.
.
child : 2 x 10 = 20
我已经使用信号量尝试了下面的代码。
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
sem_t mutex_odd,mutex_even;
int main()
{
int o=1;e=2;
pid_t pid = fork();
sem_init(&mutex_odd,0,1);
sem_init(&mutex_even,0,1);
if(pid>0)
{
while(o<=9)
{
sem_wait(&mutex_even);
printf("parent : 2 x %d = %dn", o, 2*o);
o+=2;
sem_post(&mutex_odd);
}
}
else if(pid == 0)
{
while(e<=10)
{
sem_wait(&mutex_odd);
printf("parent : 2 x %d = %dn", e, 2*e);
e+=2;
sem_post(&mutex_even);
}
}
else
{
printf("Child process couldn't be created!n");
exit(0);
}
return 0;
}
但输出如下所示。控制只是停留在那里,而不会终止程序。
parent : 2 x 1 = 2
child : 2 x 2 = 4
这是一个僵局状态吗?如何解决这个问题?
当父进程分叉时,其子进程继承父进程所管理的值的 COPY 。副本不使用相同的物理内存区域;此外,内存指针虽然看起来具有相同的地址值,但并不指向相同的物理内存区域。
获得父级和子级共享内存的方法是使用 IPC(进程间通信(函数。
下面的程序使用IPC函数:shmget
,shmat
分配内存来管理信号量(变量mutex
(,并使用shmdt
函数"解除分配"mutex
数组指针和smdctl
来删除分配的物理内存。
代码的另一个问题是信号量的初始化。第二个参数(pshared
(在分叉进程之间共享时,应为1。为了避免同步问题,第三个参数(value
(最好将父进程等待的互斥锁设置为 1,为子进程等待的互斥锁设置为 0。
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
static sem_t * mutex;
int main()
{
int o=1,e=2,r;
pid_t pid;
int shmid=0;
shmid=shmget(0,sizeof(mutex)*2 + SHMLBA, IPC_CREAT | SHM_R | SHM_W);
if (shmid==-1) {
perror("shmget");
return errno;
}
mutex=shmat(shmid, NULL, 0);
if (mutex== (void *) -1){
perror("shmat");
return errno;
}
r=sem_init(&mutex[0],1,1);
if (r) {
perror("m0");
return errno;
}
r=sem_init(&mutex[1],1,0);
if (r) {
perror("m1");
return errno;
}
pid=fork();
if(pid>0)
{
while(o<=9)
{
sem_wait(&mutex[0]);
printf("parent : 2 x %d = %dn", o, 2*o);
o+=2;
sem_post(&mutex[1]);
}
// Waits end of
waitpid(pid,NULL,0); // Waits end of child
puts("End");
r=shmdt(mutex); // Free memory
if (r)
perror("shmdt");
r=shmctl(shmid,IPC_RMID,NULL); // Remove map id.
if (r)
perror("shmctl");
}
else if(pid == 0)
{
while(e<=10)
{
sem_wait(&mutex[1]);
printf("child : 2 x %d = %dn", e, 2*e);
e+=2;
sem_post(&mutex[0]);
}
}
/*---------------------*/
else
{
perror("Child process couldn't be created!n");
exit(0);
}
return 0;
}
相关文章:
- 删除旧的信号量系统V
- 父进程和子进程之间的 POSIX 信号量
- 访问共享内存而不使用易失性、std::atomic、信号量、互斥锁和自旋锁
- 多线程.如果我使用信号量,我可以在开始时创建很多线程还是应该只有几个线程?
- C/C++ - 用于按顺序打印数字的 sem_t 类型的单个信号量
- 单车道桥 使用信号量进行同步
- 用于 64 位/32 位 IPC 的 POSIX 信号量的替代方案?
- 这个餐饮哲学家问题(dpp)的解决方案是如何工作的?互斥体和信号量
- 发布信号量返回错误 6(无效句柄)
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 在使用 pthread 和信号量实现生产者-消费者问题时需要帮助
- 如何让一个线程继续,而另一个线程正在等待C++中的信号量
- 实现信号量
- 计算信号量还是互斥体?
- POSIX 信号量在高争用/负载下不起作用
- C++:提升:托管共享内存是否需要信号量锁
- 信号量的问题
- 如何使用Windows API直接将进程"assign"到信号量?
- 生产者 - 消费者生产商创建2个元素POSIX信号量
- 了解posix进程间信号量