08利用共享内存实现父子进程间通信,子进程写入“hello father!”,父进程将子进程写入的内容读出后打印到屏幕,同时打印子进程的ID号(最后一次测试)

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

#define SHM_SIZE 128

int main() {
    int shmid;
    key_t key;
    char *shm;

    // 创建共享内存段
    key = ftok(".", 'S'); // 生成唯一的key值
    shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
    if (shmid == -1) {
        perror("shmget");
        exit(1);
    }

    // 将共享内存连接到当前进程的地址空间
    shm = shmat(shmid, NULL, 0);
    if (shm == (char *)-1) {
        perror("shmat");
        exit(1);
    }

    // 创建子进程
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(1);
    } else if (pid == 0) {
        // 子进程写入数据到共享内存
        sprintf(shm, "hello father!");
        exit(0);
    } else {
        // 父进程等待子进程结束并读取共享内存中的数据
        wait(NULL);
        printf("子进程ID号:%d\n", pid);
        printf("子进程写入的内容:%s\n", shm);

        // 分离共享内存
        if (shmdt(shm) == -1) {
            perror("shmdt");
            exit(1);
        }

        // 删除共享内存
        if (shmctl(shmid, IPC_RMID, NULL) == -1) {
            perror("shmctl");
            exit(1);
        }
    }

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值