【发布时间】: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 标志的示例。我会在声明中的哪个位置添加这个标记?