ubuntu

ubuntu进程间通信方法有哪些

小樊
59
2025-09-02 09:31:03
栏目: 智能运维

Ubuntu系统中的进程间通信(IPC)有多种方法,以下是一些常见的IPC机制:

1. 管道(Pipes)

2. 消息队列(Message Queues)

3. 共享内存(Shared Memory)

4. 信号(Signals)

5. 信号量(Semaphores)

6. 套接字(Sockets)

7. 文件锁(File Locking)

8. 内存映射文件(Memory-Mapped Files)

9. 远程过程调用(RPC)

10. D-Bus

11. ZeroMQ

12. MPI(Message Passing Interface)

使用示例

管道示例

#include <stdio.h>
#include <unistd.h>

int main() {
    int pipefd[2];
    pid_t pid;
    char buffer[10];

    if (pipe(pipefd) == -1) {
        perror("pipe");
        return 1;
    }

    pid = fork();
    if (pid == -1) {
        perror("fork");
        return 1;
    }

    if (pid > 0) { // Parent process
        close(pipefd[0]); // Close unused read end
        write(pipefd[1], "Hello from parent", 20);
        close(pipefd[1]);
    } else { // Child process
        close(pipefd[1]); // Close unused write end
        read(pipefd[0], buffer, 10);
        printf("Child received: %s\n", buffer);
        close(pipefd[0]);
    }

    return 0;
}

共享内存示例

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

int main() {
    key_t key = 1234;
    int shmid;
    char *str;

    // Create the shared memory segment
    shmid = shmget(key, 1024, IPC_CREAT | 0666);
    if (shmid == -1) {
        perror("shmget");
        exit(1);
    }

    // Attach the shared memory segment to the address space of the calling process
    str = (char *) shmat(shmid, NULL, 0);
    if (str == (char *) -1) {
        perror("shmat");
        exit(1);
    }

    // Write to the shared memory
    strcpy(str, "Hello from shared memory!");

    // Detach the shared memory segment
    shmdt(str);

    // Remove the shared memory segment
    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}

选择合适的IPC机制取决于具体的应用场景和需求。例如,如果需要高速数据交换且进程间有亲缘关系,共享内存可能是最佳选择;而如果需要在不同主机上的进程间通信,套接字则更为合适。

0
看了该问题的人还看了