这是我想在父进程和子进程之间实现信号量的程序,它们试图访问一个名为 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;
}