centos

CentOS系统中进程间通信方式

小樊
41
2025-10-15 11:05:02
栏目: 智能运维

在CentOS系统中,进程间通信(IPC)主要有以下几种方式:

1. 管道(Pipes)

2. 消息队列(Message Queues)

3. 共享内存(Shared Memory)

4. 信号量(Semaphores)

5. 套接字(Sockets)

6. 信号(Signals)

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

8. 文件锁(File Locking)

9. 信号槽机制(Signals and Slots)

实现示例

匿名管道

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

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

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

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

    if (pid == 0) { // 子进程
        close(pipefd[1]); // 关闭写端
        read(pipefd[0], buffer, sizeof(buffer));
        printf("Child received: %s\n", buffer);
        close(pipefd[0]);
    } else { // 父进程
        close(pipefd[0]); // 关闭读端
        write(pipefd[1], "Hello from parent", 20);
        close(pipefd[1]);
    }

    return 0;
}

命名管道

# 创建命名管道
mkfifo myfifo

# 写入数据
echo "Hello" > myfifo &

# 读取数据
cat myfifo

共享内存

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

int main() {
    key_t key = ftok("shmfile", 65);
    int shmid = shmget(key, 1024, 0666|IPC_CREAT);
    char *str = (char*) shmat(shmid, (void*)0, 0);

    strcpy(str, "hello world");
    printf("Shared memory segment: %s\n", str);

    shmdt(str);
    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}

信号量

#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>

union semun {
    int val;
    struct semid_ds *buf;
    unsigned short *array;
};

int main() {
    key_t key = ftok("semfile", 65);
    int semid = semget(key, 1, 0666|IPC_CREAT);

    union semun arg;
    arg.val = 1; // 初始化信号量为1
    semctl(semid, 0, SETVAL, arg);

    // P操作(等待信号量)
    struct sembuf sb = {0, -1, SEM_UNDO};
    semop(semid, &sb, 1);

    printf("Semaphore value: %d\n", semctl(semid, 0, GETVAL, arg));

    // V操作(释放信号量)
    sb.sem_op = 1;
    semop(semid, &sb, 1);

    semctl(semid, 0, IPC_RMID, arg);

    return 0;
}

这些示例展示了如何在CentOS系统中使用不同的IPC机制。根据具体需求选择合适的通信方式。

0
看了该问题的人还看了