Предположим, у меня есть 3 процесса, и я хочу, чтобы процесс 3 запускался раньше процесса 1, как мне это сделать? Или возможно ли это сделать?
Код: Выделить всё
#include
#include
#include
#include
#include
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.
Подробнее здесь: https://stackoverflow.com/questions/784 ... in-c-linux