0

当我运行这个程序时:

#include <sys/types.h>
#include <pthread.h>
#include <sys/mman.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

int main () {

    int stat;

    pthread_mutex_t *mutex = (pthread_mutex_t*)mmap (0, sizeof (pthread_mutex_t) + sizeof (long),PROT_READ | PROT_WRITE,
                                                     MAP_SHARED ,-1, 0);

    long *data = (long*)(&mutex[1]); /* map 'data' after mutex */
    int pid;

    pthread_mutexattr_t attr;
    pthread_mutexattr_init (&attr);
    pthread_mutexattr_setpshared (&attr, PTHREAD_PROCESS_SHARED);
    pthread_mutex_init (mutex, &attr);

    *data = 0;

    pid = fork ();

    pthread_mutex_lock (mutex);
    (*data)++;
    pthread_mutex_unlock (mutex);

    if (!pid) /* child exits */
        exit (0);
    else
        waitpid (pid, &stat, 0);
    printf ("data is %ld\n", *data);

    return 0;
}

我有segmentation fault!请问有什么问题?我能做些什么来解决这个错误?

调试后valgrind,我有这个消息:

==28660== Process terminating with default action of signal 11 (SIGSEGV)
==28660==  Access not within mapped region at address 0xF
==28660==    at 0x4E35C10: pthread_mutex_init (pthread_mutex_init.c:83)
==28660==    by 0x4008F0: main (in /home/program)
==28660==  If you believe this happened as a result of a stack
==28660==  overflow in your program's main thread (unlikely but
==28660==  possible), you can try to increase the size of the
==28660==  main thread stack using the --main-stacksize= flag.
==28660==  The main thread stack size used in this run was 8388608.
4

3 回答 3

3

如果您尝试在mmap没有文件描述符的情况下调用(不受文件或设备支持),则应设置该MAP_ANONYMOUS标志。没有MAP_ANONYMOUS,您将收到EBADF错误消息。

fd不是有效的文件描述符(并且MAP_ANONYMOUS未设置)。

MAP_SHARED | MAP_ANONYMOUS如果没有文件或设备支持,请尝试用作标志。

IE:

pthread_mutex_t *mutex = (pthread_mutex_t*)mmap (0, sizeof (pthread_mutex_t) + sizeof (long),PROT_READ | PROT_WRITE,
                                                 MAP_SHARED | MAP_ANONYMOUS ,-1, 0);
于 2012-11-27T09:17:31.830 回答
2

mmap(void *start, size_t length, int prot , int flags, int fd, off_t offset);用 fd -1 打电话。据我所知,使用 -1 调用 mmap 是无效的。

检查if (mutex == MAP_FAILED)mmap是否成功,如果失败,通过检查找出mmap产生了哪个错误errno

于 2012-11-27T09:12:09.363 回答
1

我尝试编译并运行您的程序。即使我也面临同样的问题,分段错误。

解决方案:如果您传递值为“-1”的 fd,请养成使用“MAP_ANON”标志的习惯,例如(MAP_SHARED | MAP_ANON)。

希望这能解决你的问题:)

于 2012-11-27T11:31:04.400 回答