简体   繁体   English

麻烦编译信号量示例

[英]trouble compiling semaphore examples

I'm trying to learn about semaphores, but I'm having the same error occur every time I try to compile an example (I've tried about 4 now). 我试图了解信号量,但是每次尝试编译一个示例时,都会遇到相同的错误(我现在尝试了大约4个)。

So the following code is not my own but taken from here: " http://blog.superpat.com/2010/07/14/semaphores-on-linux-sem_init-vs-sem_open/ " 因此,以下代码不是我自己的,而是从此处获取的:“ 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);
}

So the issue is that every time I compile this code (and other examples) I get the compiling error: " error: ":21:68: error: invalid conversion from 'void*' to 'int*' [-fpermissive]" 因此,问题在于,每次我编译此代码(和其他示例)时,我都会收到编译错误:“错误:”:21:68:错误:从'void *'到'int *'[-fpermissive]的无效转换”

Referring to this line: 引用此行:

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

Any idea why? 知道为什么吗?

1) Do not compile C code with C++ Compiler. 1)不要使用C ++编译器编译C代码。 Both C and C++ is different. C和C ++都不同。

2) C allows assigning (void *) to any other pointer type without explicit type casting. 2)C允许将(void *)分配给任何其他指针类型,而无需显式类型转换。

 For example: 

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

3) c++ DOES NOT allow assigning (void *) to any other pointer type unless EXPLICIT TYPE CASTING. 3)c ++不允许将(void *)分配给任何其他指针类型,除非使用EXPLICIT TYPE CASTING。

4) So, use gcc instead g++. 4)因此,请使用gcc代替g ++。

Hope it helps to understand some extend. 希望它有助于理解一些扩展。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM