例如信号用C [英] Semaphore example in C
问题描述
我试图使℃的简单信号的例子
中,有两个while循环,会产生这样的结果,而不线程,使用两个diferrent进程:
I am trying to make a simple semaphore example in C
in which, having two while loops, will produce this outcome without threads, using two diferrent processes :
abcd
abcd
abcd
abcd
既然不能使用pthreads的,我试图让普通信号()
和等待()
方法,但因为某些原因,我得到了唤醒一个错误
我的信号内部通话
方法。
Since I cannot use pthreads, I tried to make the common signal()
and wait()
methods but for some reasons, I get an error in the wakeup
call inside my signal
method.
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
wait(sem_t *s)
{
s=s-1;
if (s<0)
block(); // add process to queue
}
signal(sem_t *s)
{
s=s+1;
if (s<=0)
wakeup(p); // remove process p from queue
}
init(sem_t *s , int v)
{
s=v;
}
void main(void)
{
int i;
// place semaphore in shared memory
sem_t *child_sem = mmap(NULL,sizeof(*child_sem),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);
sem_t *parent_sem = mmap(NULL,sizeof(*parent_sem),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);
init(child_sem, 1); // create child semaphore
init(parent_sem, 1); // create parent semaphore
if (fork())
{
for (i = 0; i < 10; i++)
{
if (wait(child_sem) < 0)
perror("sem_wait");
printf("ab");
if (signal(parent_sem) < 0)
perror("sem_post");
sleep(1); // required to maintain thread order
}
}
else
{
for (i = 0; i < 10; i++)
{ // parent starts waiting
if (wait(parent_sem) < 0)
perror("sem_wait");
printf("cd\n");
if (signal(child_sem) < 0)
perror("sem_post");
}
}
}
输出:
[Error] In function 'signal':
[Error] 'p' undeclared (first use in this function)
的事情是,我怎么能进入警醒内的进程p?
我应该使用 PID =叉()
的方法里面呢?
我应该使用信号
方法一个额外的参数,但它会是个什么样子? PID P
?
Should I use an extra argument in signal
method but what would it be like? pid p
?
如果我从除去p-参数唤醒
,然后像 PROT_READ
变量成为未申报的某些原因。
If I remove the p argument from wakeup
, then variables like PROT_READ
become undeclared for some reason.
P.S。在code是从该网站。
P.S. The code is from this site.
推荐答案
我不会写了整个事情,但这里是解决这个问题的更好的方法。
I will not write the the whole thing but here is a better way to solve this.
- 使用2信号灯。
- 运行的第一个进程时,信号1号高
- 运行第二个进程时,信号2号高
- 在第1过程的关键部分的起点,使第2信号的低,使得该资源不能由第2方法中使用
- 在第1过程的关键部分的端部,使第2信号= 1和第1信号= 0
- 请第二个过程正好相反,即说明SEM1 = 0,结束SEM1 = 1,sem2 = 0。
这可能会解决问题即可。切勿使用信号
使用的sigaction
代替。
This may solve the problem. Never use signal
use sigaction
instead.
这篇关于例如信号用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!