[英]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.