【作业day3】

1.管道:

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

int main() {
    int pipe_fd[2];
    char message[] = "Hello, IPC!";

    if (pipe(pipe_fd) == -1) {
        perror("Pipe creation failed");
        return 1;
    }

    pid_t child_pid = fork();

    if (child_pid == -1) {
        perror("Fork failed");
        return 1;
    }

    if (child_pid == 0) {  
        close(pipe_fd[1]);  
        char buffer[100];
        read(pipe_fd[0], buffer, sizeof(buffer));
        printf("Child received: %s\n", buffer);
        close(pipe_fd[0]);
    } else {  
        close(pipe_fd[0]);  
        write(pipe_fd[1], message, sizeof(message));
        close(pipe_fd[1]);
    }

    return 0;
}

2.共享内存:

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

int main() {
    key_t key = ftok("shm_example", 65);
    int shmid = shmget(key, 1024, 0666|IPC_CREAT);

    char *shared_memory = (char*) shmat(shmid, (void*)0, 0);

    pid_t child_pid = fork();

    if (child_pid == -1) {
        perror("Fork failed");
        return 1;
    }

    if (child_pid == 0) {  
        printf("Child received: %s\n", shared_memory);
    } else {  
        sprintf(shared_memory, "Hello, IPC!");
        wait(NULL);
        shmdt(shared_memory);
        shmctl(shmid, IPC_RMID, NULL);
    }

    return 0;
}

3.消息队列:

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

struct msg_buffer {
    long msg_type;
    char msg_text[100];
};

int main() {
    key_t key = ftok("msgq_example", 65);
    int msgid = msgget(key, 0666|IPC_CREAT);

    struct msg_buffer message;

    pid_t child_pid = fork();

    if (child_pid == -1) {
        perror("Fork failed");
        return 1;
    }

    if (child_pid == 0) { 
        msgrcv(msgid, &message, sizeof(message), 1, 0);
        printf("Child received: %s\n", message.msg_text);
    } else {  
        message.msg_type = 1;
        sprintf(message.msg_text, "Hello, IPC!");
        msgsnd(msgid, &message, sizeof(message), 0);
    }

    return 0;
}
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值