简体   繁体   中英

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).

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/ "

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

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. Both C and C++ is different.

2) C allows assigning (void *) to any other pointer type without explicit type casting.

 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.

4) So, use gcc instead g++.

Hope it helps to understand some extend.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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