這是一個程序,我希望在父進程和子進程之間實現信號量,這些進程正試圖訪問一個名爲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;
}
我會嘗試調試。 – akonsu
好的調試分叉進程是非平凡的... @OP fork創建進程不是線程 – LostBoy