C++在Linux中的进程间通信

发布时间:2024-12-19 18:26:13 作者:小樊
来源:亿速云 阅读:78

在Linux环境下,C++程序可以通过多种进程间通信(IPC)机制进行有效的数据交换和同步。以下是一些常用的IPC方法及其特点:

管道(Pipe)

int pipefd[2];
if (pipe(pipefd) == -1) {
    std::cerr << "创建管道失败" << std::endl;
    return 1;
}
pid_t pid = fork();
if (pid == -1) {
    std::cerr << "创建子进程失败" << std::endl;
    return 1;
} else if (pid == 0) {
    close(pipefd[0]);
    const char *msg = "Hello, Parent!";
    write(pipefd[1], msg, strlen(msg));
    close(pipefd[1]);
} else {
    close(pipefd[1]);
    char buffer[100];
    read(pipefd[0], buffer, sizeof(buffer));
    std::cout << "Received: " << buffer << std::endl;
    close(pipefd[0]);
}

命名管道(FIFO)

int pipefds[2];
if (pipe(pipefds) == -1) {
    std::cerr << "Pipe failed" << std::endl;
    return 1;
}
pid_t pid = fork();
if (pid == -1) {
    std::cerr << "Fork failed" << std::endl;
    return 1;
} else if (pid == 0) {
    close(pipefds[1]);
    char buffer[1024];
    read(pipefds[0], buffer, sizeof(buffer));
    std::cout << "Child received: " << buffer << std::endl;
    close(pipefds[0]);
} else {
    close(pipefds[0]);
    std::string message = "Hello, child process!";
    write(pipefds[1], message.c_str(), message.size());
    close(pipefds[1]);
}

消息队列(Message Queue)

key_t key = ftok("queuefile", 65);
int msgid = msgget(key, 0666 | IPC_CREAT);
struct message {
    long msg_type;
    char msg_text[100];
};
message msg;
msg.msg_type = 1;
strcpy(msg.msg_text, "Hello from process");
msgsnd(msgid, &msg, sizeof(msg.msg_text), 0);
msgrcv(msgid, &msg, sizeof(msg.msg_text), 1, 0);
std::cout << "Received: " << msg.msg_text << std::endl;
msgctl(msgid, IPC_RMID, NULL);

共享内存(Shared Memory)

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, Shared Memory!");
std::cout << "Data written in memory: " << str << std::endl;
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);

信号量(Semaphore)

union semun {
    int val;
    struct semid_ds *buf;
    unsigned short *arry;
};
static int sem_id = 0;
static int set_semvalue() {
    union semun sem_union;
    sem_union.val = 1;
    if (semctl(sem_id, 0, SETVAL, sem_union) == -1) return 0;
    return 1;
}
static void del_semvalue() {
    union semun sem_union;
    if (semctl(sem_id, 0, IPC_RMID) == -1) {}
}
static int semaphore_p() {
    if (sem_id == 0) return -1;
    if (semctl(sem_id, 0, SETVAL, sem_union) == -1) return -1;
    if (sem_op(sem_id, 0, 1) == -1) return -1;
    return 0;
}
static int semaphore_v() {
    union semun sem_union;
    sem_union.val = 1;
    if (semctl(sem_id, 0, SETVAL, sem_union) == -1) return -1;
    return 0;
}

每种IPC方法都有其特定的使用场景和性能特点,开发者应根据具体需求选择合适的IPC机制。

推荐阅读:
  1. 如何制作一个 RPM 文件
  2. Linux Shell命令cd和ls的用法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

linux

上一篇:Linux下C++的并发编程模型

下一篇:如何在Linux上使用C++进行网络爬虫开发

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》