C、Linux 中的同步进程

问题描述 投票:0回答:1

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

c linux multithreading operating-system
1个回答
0
投票

您需要使用“共享”信号量在进程之间共享/发出信号。非共享信号量(就像您正在使用的)只能同步单个进程中的线程。

要创建共享信号量,您需要将其分配在共享内存中,这有点棘手。最简单的方法就是使用

sem_t *semaphore = mmap(0, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
if (!semaphore || sem_init(semaphore, 1, 0) == -1) {
    perror("Semaphore initialization failed");
    exit(EXIT_FAILURE);
}
© www.soinside.com 2019 - 2024. All rights reserved.