我正在尝试创建一个 C 程序,其中通过使用 POSIX 信号量函数在父项和子项之间交替来递增计数器。到目前为止,考虑到这是我第一次使用信号量函数,我在使用它时遇到了麻烦。如果我的程序有任何问题,一些指针会很棒。
到目前为止,孩子似乎根本没有增加,我不确定为什么会这样。该程序在开始时也表现得很奇怪,因为它先留在孩子体内,然后再与父母交替。
到目前为止,该计划的结果:
GOT EM - parent: expected 0, got 0
GOT EM - child: expected 1, got 1
child: expected 3, got 1
child: expected 5, got 1
child: expected 7, got 1
child: expected 9, got 1
child: expected 11, got 1
child: expected 13, got 1
child: expected 15, got 1
child: expected 17, got 1
child: expected 19, got 1
child: expected 21, got 1
child: expected 23, got 1
child: expected 25, got 1
child: expected 27, got 2
child: expected 29, got 2
child: expected 31, got 2
child: expected 33, got 2
child: expected 35, got 2
child: expected 37, got 2
GOT EM - parent: expected 2, got 2
child: expected 39, got 2
child: expected 41, got 3
GOT EM - parent: expected 4, got 4
child: expected 43, got 4
GOT EM - parent: expected 6, got 6
child: expected 45, got 6
GOT EM - parent: expected 8, got 8
child: expected 47, got 8
GOT EM - parent: expected 10, got 10
child: expected 49, got 10
我的程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <semaphore.h>
#define NLOOPS 1000
#define SIZE sizeof(long) /* size of shared memory area */
struct shmbuf{
sem_t child;
sem_t parent;
};
static int update(long *ptr)
{
return((*ptr)++); /* return value before increment */
}
int main(void)
{
int fd, i, counter;
pid_t pid;
struct shmbuf *shmp;
if ((fd = open("/dev/zero", O_RDWR)) < 0)
perror("open error");
ftruncate(fd, sizeof(struct shmbuf));
if ((shmp = mmap(0, sizeof(struct shmbuf), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED)
perror("mmap error");
close(fd);
sem_init(&shmp->child, 1, 0);
sem_init(&shmp->parent, 1, 1); /* Parent first */
if ((pid = fork()) < 0) {
perror("fork error");
} else if (pid > 0) { /* parent */
for (i = 0; i < NLOOPS; i += 2) {
sem_wait(&shmp->parent);
if ((counter = update((long *)shmp)) != i)
printf(" parent: expected %d, got %d\n", i, counter);
else
printf("GOT EM - parent: expected %d, got %d\n", i, counter);
sem_post(&shmp->child);
}
} else { /* child */
for (i = 1; i < NLOOPS + 1; i += 2) {
sem_wait(&shmp->child);
if ((counter = update((long *)shmp)) != i)
printf(" child: expected %d, got %d\n", i, counter);
else
printf("GOT EM - child: expected %d, got %d\n", i, counter);
sem_post(&shmp->parent);
}
}
exit(0);
}