-1

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?

2 Answers2

2

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.

Whoami
  • 13,930
  • 19
  • 84
  • 140
1

You are trying to compile this C code as C++, and C++ has stricter rules regarding automatically converting pointer types.

hcs
  • 1,514
  • 9
  • 14