C语言 当我使用 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 %ldn", *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.

如果您尝试在没有文件描述符(不受文件或设备支持)的情况下调用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);

你用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 产生的错误

我尝试编译和运行您的程序。甚至我也面临着同样的问题,分割错误。

溶液: 如果您传递的值为"-1"的 fd,请养成使用"MAP_ANON"标志的习惯 即例如(MAP_SHARED |MAP_ANON)。

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

相关内容

  • 没有找到相关文章

最新更新