c - 父子进程之间的信号量

标签 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;
}

最佳答案

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

关于c - 父子进程之间的信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19551695/

相关文章:

c# - 在接收 Process.Exited 事件时更新父进程 GUI - WPF

2 个 2D vector 的叉积

c - ISO C90 禁止混合声明和代码 - 为什么

c - GDB结构输出

linux - 如何使用 `pstree` 获取所有父进程和所有子进程

Linux内核内存管理,它是否一直使用连续的内存页?

linux - 在 Raspberry Pi 上安装 Go 包

c - 使用 c 检测文件中的重复行

c - 使用 libproc 获取子进程

Haskell:启动一个长时间运行的进程,默默地捕获标准输出