簡體   English   中英

麻煩編譯信號量示例

[英]trouble compiling semaphore examples

我試圖了解信號量,但是每次嘗試編譯一個示例時,都會遇到相同的錯誤(我現在嘗試了大約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);
}

因此,問題在於,每次我編譯此代碼(和其他示例)時,我都會收到編譯錯誤:“錯誤:”:21:68:錯誤:從'void *'到'int *'[-fpermissive]的無效轉換”

引用此行:

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

知道為什么嗎?

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 *)分配給任何其他指針類型,除非使用EXPLICIT TYPE CASTING。

4)因此,請使用gcc代替g ++。

希望它有助於理解一些擴展。

您正在嘗試將此C代碼編譯為C ++,並且C ++對於自動轉換指針類型具有更嚴格的規則。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM