这个问题比较难,但我想理解一个更简单的例子。假设我有 3 个进程,我希望进程 3 在进程 1 之前启动,我该怎么做?或者说,有可能做到吗?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <semaphore.h>
int main() {
sem_t semaphore;
// Initialize semaphore with initial value 0
if (sem_init(&semaphore, 0, 0) == -1) {
perror("Semaphore initialization failed");
exit(EXIT_FAILURE);
}
// Create child process 1
if (fork() == 0) {
// Child process 1 (Process 1) starts here
printf("Process 1 started.\n");
// Wait for signal from Process 3
sem_wait(&semaphore);
printf("Process 1 completed its work.\n");
exit(0);
}
// Create child process 2
if (fork() == 0) {
// Child process 2 (Process 2) starts here
printf("Process 2 started.\n");
printf("Process 2 completed its work.\n");
exit(0);
}
// Create child process 3
if (fork() == 0) {
// Child process 3 (Process 3) starts here
printf("Process 3 started.\n");
// Signal Process 1 to start
sem_post(&semaphore);
exit(0);
}
wait(NULL);
wait(NULL);
wait(NULL);
// Destroy semaphore
sem_destroy(&semaphore);
return 0;
}
这是我得到的输出:
Process 1 started.
Process 3 started.
Process 2 started.
Process 2 completed its work.
就像陷入无限循环一样,进程 1 和进程 3 不会终止。
您需要使用“共享”信号量在进程之间共享/发出信号。非共享信号量(就像您正在使用的)只能同步单个进程中的线程。
要创建共享信号量,您需要在共享内存中分配它,这有点棘手。最简单的方法是使用
这有点低效,因为它为信号量分配整个页面(通常为 4096 字节),浪费了大部分空间(mmap 会将请求的大小四舍五入为页面大小的倍数)。
如果需要多个信号量,可以通过一次调用 mmap 将它们分配为数组。如果您需要更多共享内存(例如用于进程之间通信的缓冲区),您可以将所需的所有内容收集到一个大型结构中,并使用
mmap