Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Программирование под Unix/Linux > Ошибка в программе


Автор: Competitor 2.4.2006, 21:42
Программа увеличивает счетчик в отображаемом в память файле. (QNX 6.3.0)
Код

#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <sys/mman.h>
#define MAXLINE 4096
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
#define SEM_NAME "mysem"

struct shared {
 sem_t mutex; /* the mutex: a Posix memory-based semaphore */
 int count;        /* and the counter */
} shared;

int main(int argc, char **argv)
{
    int fd, i, nloop;
    struct shared  *ptr;
    if (argc != 3)
        printf("usage: incr3 <pathname> <#loops>");
    nloop = atoi(argv[2]);
        /* 4open file, initialize to 0, map into memory */
    fd = open(argv[1], O_RDWR | O_CREAT, FILE_MODE);
    write(fd, &shared, sizeof(struct shared));
    ptr = mmap(NULL, sizeof(struct shared), PROT_READ | PROT_WRITE,
               MAP_SHARED, fd, 0);
    close(fd);
        /* 4initialize semaphore that is shared between processes */
    sem_init(&ptr->mutex, 1, 1);
    setbuf(stdout, NULL);    /* stdout is unbuffered */
    if (fork() == 0) {        /* child */
        for (i = 0; i < nloop; i++) {
            sem_wait(&ptr->mutex);
            printf("child: %d\n", ptr->count++);
            sem_post(&ptr->mutex);
        }
        exit(0);
    }
        /* 4parent */
    for (i = 0; i < nloop; i++) {
        sem_wait(&ptr->mutex);
        printf("parent: %d\n", ptr->count++);
        sem_post(&ptr->mutex);
    }
    exit(0);
}


Компилируется без ошибок. При запуске выдает: "Memory fault (core dumped)".
Как исправить?
Не нравятся ему скорей всего строки:
Код

sem_wait(&ptr->mutex);
printf("child: %d\n", ptr->count++);

За раннее благодарен

Автор: GrayCardinal 9.4.2006, 20:47
Угу. А оно вообще mmap-иться ? Т.е. значение ptr неплохо было бы проверить на
MAP_FAILED (that is, (void *) -1)

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)