【问题标题】:trouble compiling semaphore examples编译信号量示例的麻烦
【发布时间】:2014-04-28 08:10:16
【问题描述】:

我正在尝试学习信号量,但每次尝试编译示例时都会出现相同的错误(我现在尝试了大约 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: error: invalid conversion from 'void*' to 'int*' [- fpermissive]"

参考这一行:

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

知道为什么吗?

【问题讨论】:

  • 您使用哪种操作系统和编译器?我已经在我的Linux环境下编译过了,没问题。
  • 我正在使用 ubuntu。我用g++编译,是不是这个问题
  • 哈哈,这快把我逼疯了。你是怎么编译的?
  • 你应该使用“gcc”而不是“g++”。
  • 好的,这行得通。我正在查看另一个需要添加 -pthread 标志的示例。我会在声明中的哪个位置添加这个标记?

标签: c unix semaphore


【解决方案1】:

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 *) 分配给任何其他指针类型,除非显式类型转换。

4) 所以,用 gcc 代替 g++。

希望它有助于理解一些扩展。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多