麻烦编译信号量的例子

时间:2014-03-21 05:05:11

标签: c unix semaphore

我正在尝试学习信号量,但每次我尝试编译一个例子时都会出现同样的错误(我现在已经尝试了4个)。

所以下面的代码不是我自己的代码,而是从这里开始:“http://blog.superpat.com/2010/07/14/semaphores-on-linux-sem_init-vs-sem_open/

#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>

int main(int argc, char **argv)
{
  int fd, i,count=0,nloop=10,zero=0,*ptr;
  sem_t mutex;

  //open a file and map it into memory

  fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU);
  write(fd,&zero,sizeof(int));
  ptr = mmap(NULL,sizeof(int),PROT_READ |PROT_WRITE,MAP_SHARED,fd,0);
  close(fd);

  /* create, initialize semaphore */
  if( sem_init(&mutex,1,1) < 0)
    {
      perror("semaphore initilization");
      exit(0);
    }
  if (fork() == 0) { /* child process*/
    for (i = 0; i < nloop; i++) {
      sem_wait(&mutex);
      printf("child entered crititical section: %d\n", (*ptr)++);
      sleep(2);
      printf("child leaving critical section\n");
      sem_post(&mutex);
      sleep(1);
    }
    exit(0);
  }
  /* back to parent process */
  for (i = 0; i < nloop; i++) {
    sem_wait(&mutex);
    printf("parent entered critical section: %d\n", (*ptr)++);
    sleep(2);
    printf("parent leaving critical section\n");
    sem_post(&mutex);
    sleep(1);
  }
  exit(0);
}

所以问题是每次我编译这段代码(和其他例子)我都会得到编译错误:“error:”:21:68:错误:从'void *'转换为'int *'无效[ - fpermissive]“

参考这一行:

ptr = mmap(NULL,sizeof(int),PROT_READ |PROT_WRITE,MAP_SHARED,fd,0);
  close(fd);

知道为什么吗?

2 个答案:

答案 0 :(得分:2)

1)不要用C ++编译器编译C代码。 C和C ++都不同。

2)C允许在没有显式类型转换的情况下将(void *)赋值给任何其他指针类型。

 For example: 

           char * p = malloc (10); // where as return type of malloc is void *

3)c ++不允许将(void *)赋值给任何其他指针类型,除非显性类型为CASTING。

4)所以,使用gcc而不是g ++。

希望在某种程度上理解它有所帮助。

答案 1 :(得分:1)

您正在尝试将此C代码编译为C ++,并且C ++有更严格的规则来自动转换指针类型。