用于IPC的命名信号的POSIX实现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用于IPC的命名信号的POSIX实现相关的知识,希望对你有一定的参考价值。
我正在从事一项家庭作业,其中涉及实施信号灯以强制子进程之间相互排斥。除了没有正确使用信号灯之外,我的大部分代码都在工作。我发现的文章并没有太大帮助。有人可以向我解释POSIX信号灯的工作原理吗?
例如,如果我有一个父进程,则使用fork()
和execl()
生成子进程:
sem=sem_open("/semaphore1",O_CREAT|O_EXCL,S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP,1);
for (i = 0; i < 3; i++)
{
//three child process are spawned in the image of the parent
child[i] = fork();
//establish whether all children were created successfully
switch (child[i])
{
//child process creation failed...
case -1:
rpterror ((char *)"fork failure", pname);
exit(1);
//given that the fork() was successful (the children were spawned successfully)...
case 0:
sprintf (pname, "shmc%d", i+1);
execl("shmc1", pname, ascshmid, (char *)0);
perror ("execl failed");
exit (2);
}
}
孩子们想要访问和修改共享内存段中的值(由父级创建:)]]
sem=sem_open("/semaphore1", O_RDWR); while ( !all_out) { /* loop to sell all seats */ /* puts the process to sleep for an amount of time, then decreases the amount of seats available. Before printing out the new count of seats, the process sleeps again. Finally, it prints the seat count until there are no more seats left.*/ if (class_ptr->seats_left > 0) { sem_wait(sem); sleep ( (unsigned)rand()%5 + 1); class_ptr->seats_left--; sleep ( (unsigned)rand()%5 + 1); cout << pname << " SOLD SEAT -- " << class_ptr->seats_left << " left" <<endl; sem_post(sem); } else { all_out++; cout << pname << " sees no seats left" << endl; } sleep ( (unsigned)rand()%10 + 1); }
其中
seats_left
是共享变量。
运行这段代码会给我一个看起来像这样的输出。共享变量的初始值为15:
shmc1 SOLD SEAT -- 14 left shmc2 SOLD SEAT -- 13 left shmc3 SOLD SEAT -- 12 left shmc1 SOLD SEAT -- 11 left shmc2 SOLD SEAT -- 10 left shmc3 SOLD SEAT -- 9 left shmc1 SOLD SEAT -- 8 left shmc2 SOLD SEAT -- 7 left shmc3 SOLD SEAT -- 6 left shmc2 SOLD SEAT -- 5 left shmc1 SOLD SEAT -- 4 left shmc3 SOLD SEAT -- 3 left shmc2 SOLD SEAT -- 2 left shmc1 SOLD SEAT -- 1 left shmc1 sees no seats left shmc3 SOLD SEAT -- 0 left shmc3 sees no seats left shmc2 SOLD SEAT -- -1 left shmc2 sees no seats left Parent removing shm
您可以看到,到最后,我的流程同时又进入了关键部分。有人知道为什么吗?
我正在从事一项家庭作业,其中涉及实施信号灯以强制子进程之间相互排斥。除了没有使用信号量外,我的大部分代码都可以使用...
答案
尝试将sem_wait()
移动到if
语句之外:
以上是关于用于IPC的命名信号的POSIX实现的主要内容,如果未能解决你的问题,请参考以下文章