父子进程之间的信号量

时间:2013-10-23 20:30:18

标签: c linux process fork semaphore

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

首先,你需要在sem_init()调用中为pshared使用非零值。

答案 2 :(得分:0)

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