使用fork运行两个进程时出现分段错误

时间:2012-11-27 08:54:21

标签: c segmentation-fault fork

当我运行此程序时:

#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.

3 个答案:

答案 0 :(得分:3)

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

  

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

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

即:

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);

答案 1 :(得分:2)

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

检查if (mutex == MAP_FAILED)以确定mmap是否成功,如果失败,请通过检查errno

找出mmap产生的错误

答案 2 :(得分:1)

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

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

希望这可以解决您的问题:)