Reputation: 2228
When I run this program :
#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;
}
I have segmentation fault
! What is problem please ? and what can i do to resolve this error ?
after debbuging with valgrind
, i have this message :
==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.
Upvotes: 0
Views: 1273
Reputation: 1763
I tried compiling and running your program. Even I was facing the same problem, segmentation fault.
Solution: If you are passing fd with value "-1", make it a habit of using "MAP_ANON" flag i.e. for example (MAP_SHARED | MAP_ANON).
Hope this would solve your problem :)
Upvotes: 1
Reputation: 12420
If you are trying to call mmap
without a file descriptor (not backed by a file or device), you should set the MAP_ANONYMOUS
flag. Without MAP_ANONYMOUS
, you will receive a EBADF
error.
fd
is not a valid file descriptor (andMAP_ANONYMOUS
was not set).
Try to use MAP_SHARED | MAP_ANONYMOUS
as the flag if it is not backed by a file or device.
i.e.:
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);
Upvotes: 3
Reputation: 155
You are calling mmap(void *start, size_t length, int prot , int flags, int fd, off_t offset);
with fd -1. As far as I know, calling mmap with -1 is not valid.
Check if (mutex == MAP_FAILED)
to find out if mmap succeeds, and if it fails, find out which error mmap produced by checking errno
Upvotes: 2