-1

这是我想在父进程和子进程之间实现信号量的程序,它们试图访问一个名为 counter 的共享变量......我不知道为什么它在子进程期间没有增加!请有人帮忙!

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
sem_t mutex;
int counter;
int main ()
pid_t child_pid;
sem_init(&mutex, 0, 1);
printf ("the main program process ID is %d\n", (int) getpid ());
child_pid = fork ();
if (child_pid != 0) {
printf ("This is the parent process, with id %d\n", (int) getpid ());
printf("Thread 1: Waiting to enter critical region...\n");
sem_wait(&mutex);
printf("Thread 1: Now in critical region...\n");
printf("Thread 1: Counter Value: %d\n",counter);
printf("Thread 1: Incrementing Counter...\n");
counter++;
printf("Thread 1: New Counter Value: %d\n",counter);
printf("Thread 1: Exiting critical region...\n");
sem_post(&mutex);       
}
else
{
sleep(10);
printf ("this is the child process, with id %d\n", (int) getpid ());
sem_wait(&mutex);
printf("Thread 2: Now in critical region...\n");
printf("Thread 2: Counter Value: %d\n",counter);
printf("Thread 2: Incrementing Counter...\n");
counter++;
printf("Thread 2: New Counter Value: %d\n",counter);
printf("Thread 2: Exiting critical region...\n");
sem_post(&mutex);
}
sem_destroy(&mutex);
return 0;
}
4

3 回答 3

1

您必须创建一个共享内存信号量,否则父母和孩子将拥有自己独立的信号量。

于 2015-06-21T17:00:30.923 回答
0

counter不共享,因为复制fork()了整个过程。您正在增加不同的变量。

于 2013-10-23T21:18:53.400 回答
0

一方面,您需要在 sem_init() 调用中为 pshared 使用非零值。

于 2013-10-23T20:41:06.417 回答