The problem is more difficult, but I want to understand an easier example. Let s say I have 3 processes, and I want process 3 to start before process 1, how can I do it? Or, is it possible to do it?
#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.
");
// Wait for signal from Process 3
sem_wait(&semaphore);
printf("Process 1 completed its work.
");
exit(0);
}
// Create child process 2
if (fork() == 0) {
// Child process 2 (Process 2) starts here
printf("Process 2 started.
");
printf("Process 2 completed its work.
");
exit(0);
}
// Create child process 3
if (fork() == 0) {
// Child process 3 (Process 3) starts here
printf("Process 3 started.
");
// 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并不终止。