这个问题更困难,但我想理解一个更简单的例子. 假设我有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不会终止.