例如信号用C [英] Semaphore example in C

查看:161
本文介绍了例如信号用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.


  1. 使用2信号灯。

  2. 运行的第一个进程时,信号1号高

  3. 运行第二个进程时,信号2号高

  4. 在第1过程的关键部分的起点,使第2信号的低,使得该资源不能由第2方法中使用

  5. 在第1过程的关键部分的端部,使第2信号= 1和第1信号= 0

  6. 请第二个过程正好相反,即说明SEM1 = 0,结束SEM1 = 1,sem2 = 0。

这可能会解决问题即可。切勿使用信号使用的sigaction 代替。

This may solve the problem. Never use signal use sigaction instead.

这篇关于例如信号用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆