study msg

在这里插入图片描述
sen.c

#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/wait.h"
#include "stdlib.h"
#include "string.h"
#include "errno.h"
#include "fcntl.h"
#include "sys/stat.h"
#include "sys/ipc.h"
#include "sys/msg.h"

struct msgbuf{
    long mtype;
    char mtext[1024];
};
int main(int argc,char const *argv[])
{
    while(1)
    {
        puts("please input infomation label:");
        int label;
        scanf("%d",&label);
        getchar();
        //create key
        key_t key=ftok(".",label);
        if(-1==key)
        {
            perror("ftok erro");
            exit(1);
        }
        //create msgid
        int msgid=msgget(key,IPC_CREAT|0666);
        if(-1==msgid)
        {
            perror("msgget erro");
            exit(1);
        }
        struct msgbuf *msg;
        msg = malloc(sizeof(struct msgbuf));
        msg->mtype=1;
    
        memset(msg->mtext,0,1024);
        puts("please input:");
        fgets(msg->mtext,1024,stdin);
        //int ret=msgsnd(msgid,msg,strlen(msg->mtext)+sizeof(msg->mtype),0);
        int ret=msgsnd(msgid,msg,sizeof(*msg),0);
        if(-1==ret)
        {
            perror("msgsnd erro");
            continue;
        }

        if(!strncmp(msg->mtext,"quit",4))
        {
            break;
        }
    }
    return 0;
}

recv.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct msgbuf{
    long mtype;
    char mtext[1024];
};

int main(int argc, char const *argv[])
{
    while (1)
    {
        puts("please input infomation label:");
        int label;
        scanf("%d",&label);
        getchar();
        // create key
        key_t key = ftok(".", label);
        if (-1 == key)
        {
            perror("ftok erro");
            exit(1);
        }

        // create msgid
        int msgid = msgget(key, IPC_CREAT | 0666);
        if (-1 == msgid)
        {
            perror("msgget erro");
            exit(1);
        }

        struct msgbuf msg;  // 改为局部数组
    
        memset(&msg, 0, sizeof(msg));  // 使用 memset 初始化数组

        int ret = msgrcv(msgid, &msg, sizeof(struct msgbuf), 1, 0);  // 修改为 msg 的地址
        if (-1 == ret)
        {
            perror("msgrecv erro");
            continue;
        }
        if (!strncmp(msg.mtext, "quit", 4))
        {
            break;
        }
        printf("recvbuf:%s", msg.mtext);
    }
}

优化后的信号量控制共享内存

send.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>

#define SPACE 0
#define DATA 1

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

int main(int argc,char const *argv[])
{
    key_t key =ftok(".",1);
    //create shm
    int shmid=shmget(key,1024,IPC_CREAT|0666);
    if(-1==shmid)
    {
        perror("shmget erro");
        exit(1);
    }
    //create 2 sem
    int semid=semget(key,2,IPC_CREAT|0666);
    if(-1==semid)
    {
        perror("semget erro");
        exit(1);
    }

    union semun a;
    
    //init sem
    //a.val=1;
    semctl(semid,SPACE,SETVAL,1);//space设置信号量0为1
    //a.val=0;
    semctl(semid,DATA,SETVAL,0);//data设置信号量1为0

    char *p=shmat(shmid,NULL,0);
    if(NULL==p)
    {
        perror("shmat erro");
        exit(1);
    }
    while (1)
    {
        if(semctl(semid,SPACE,GETVAL)==1 && semctl(semid,DATA,GETVAL)==0 )
        {
            //如果空间为1,且数据为0,说明没有数据所以发送数据
            printf("please input:");
            fgets(p,1024,stdin);
            semctl(semid,DATA,SETVAL,1);//发送数据后,将data设置为1
            semctl(semid,SPACE,SETVAL,0);//发送数据后,将space设置为0
            if(!strncmp(p,"quit",4))
            {
                break;
            }
        }
    }
    shmdt(p);
    return 0;
}

recv.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>

#define SPACE 0
#define DATA 1

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

int main(int argc,char const *argv[])
{
    key_t key =ftok(".",1);
    //create shm
    int shmid=shmget(key,1024,IPC_CREAT|0666);
    if(-1==shmid)
    {
        perror("shmget erro");
        exit(1);
    }
    //create 2 sem
    int semid=semget(key,2,IPC_CREAT|0666);
    if(-1==semid)
    {
        perror("semget erro");
        exit(1);
    }

    union semun a;
    
    //init sem
    //a.val=1;
    semctl(semid,SPACE,SETVAL,1);//space设置信号量0为1
    //a.val=0;
    semctl(semid,DATA,SETVAL,0);//data设置信号量1为0

    char *p=shmat(shmid,NULL,0);
    if(NULL==p)
    {
        perror("shmat erro");
        exit(1);
    }
    while(1)
    {
        if(semctl(semid,SPACE,GETVAL)==0 && semctl(semid,DATA,GETVAL)==1)
        {
            //如果空间为0,且数据为1,说明有数据所以接受数据
            printf("recv:%s",p);   
            if(!strncmp(p,"quit",4))
            {
                break;
            }
            semctl(semid,DATA,SETVAL,0);//接受数据后,将data设置为0
            semctl(semid,SPACE,SETVAL,1);//接受数据后,将space设置为1
        }
    }
    shmdt(p);
    return 0;
}
  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To apply channel coding to the transmitted data sequence, we can use the following codes: 1. Hamming Code (7,4): ```python import numpy as np from scipy import special from scipy import signal # Define the message bits msg = np.random.randint(0, 2, 1000) # Encode the message using Hamming Code (7,4) hamming_code = signal.convolve(msg, np.array([1,0,1,1]), mode='same') hamming_code = np.hstack((hamming_code.reshape(-1, 4), np.zeros((len(hamming_code)//4,3)))) # Add AWGN to the coded sequence SNR = 10 Eb_No = 10**(SNR/10) noise_std = np.sqrt(1/(2*Eb_No)) noise = np.random.normal(0, noise_std, len(hamming_code)) received_signal = hamming_code + noise # Decode the received signal using Hamming Code (7,4) dec_hamming_code = np.zeros_like(hamming_code) for i in range(len(hamming_code)//7): block = received_signal[i*7:(i+1)*7] syndrome = np.array([np.sum(block*np.array([1,1,0,1])), np.sum(block*np.array([1,0,1,1])), np.sum(block*np.array([0,1,1,1]))]) if np.sum(syndrome) == 0: dec_hamming_code[i*4:(i+1)*4] = block[[0,1,3,4]] else: error_index = np.sum(syndrome*np.array([1,2,4])) - 1 block[error_index] = 1 - block[error_index] dec_hamming_code[i*4:(i+1)*4] = block[[0,1,3,4]] # Calculate the Bit Error Rate (BER) ber_hamming_code = np.mean(np.abs(dec_hamming_code-msg)) ``` 2. BCH Code (15,7): ```python import numpy as np from scipy import special from scipy import signal # Define the message bits msg = np.random.randint(0, 2, 1000) # Encode the message using BCH Code (15,7) t = 2 n = 15 k = 7 g = np.array([1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1]) bch_encoder = signal.convolve(msg, g, mode='full') bch_encoder = bch_encoder[:len(msg)*n//k].reshape(-1, n) # Add AWGN to the coded sequence SNR = 10 Eb_No = 10**(SNR/10) noise_std = np.sqrt(1/(2*Eb_No)) noise = np.random.normal(0, noise_std, len(bch_encoder)) received_signal = bch_encoder + noise # Decode the received signal using BCH Code (15,7) bch_decoder = np.zeros_like(bch_encoder) for i in range(len(bch_encoder)): error = np.zeros(n, dtype=int) synd = signal.convolve(received_signal[i], g[::-1], mode='full')[n-1:] if np.sum(synd) != 0: pos = np.arange(0, n+1) pos = pos[synd == 1] for j in range(len(pos)): error[pos[j]-1] = 1 bch_decoder[i] = received_signal[i] ^ error else: bch_decoder[i] = received_signal[i] # Calculate the Bit Error Rate (BER) ber_bch_code = np.mean(np.abs(bch_decoder-msg)) ``` 3. Convolutional Code: ```python import numpy as np from scipy import special from scipy import signal # Define the message bits msg = np.random.randint(0, 2, 1000) # Define the generator polynomials g1 = np.array([1, 0, 1]) g2 = np.array([1, 1, 1]) # Encode the message using a Convolutional Code with rate 1/2 conv_encoder = signal.convolve(msg, g1, mode='full') conv_encoder = np.vstack((conv_encoder[::2], conv_encoder[1::2])) conv_encoder = signal.convolve(conv_encoder.flatten(), g2, mode='full') conv_encoder = np.vstack((conv_encoder[::2], conv_encoder[1::2])) # Add AWGN to the coded sequence SNR = 10 Eb_No = 10**(SNR/10) noise_std = np.sqrt(1/(2*Eb_No)) noise = np.random.normal(0, noise_std, len(conv_encoder)) received_signal = conv_encoder + noise # Decode the received signal using a Convolutional Code with rate 1/2 trellis = np.array([[0,0,0],[0,1,2],[1,3,2],[1,0,0]]) conv_decoder = np.zeros_like(conv_encoder) for i in range(len(conv_encoder)): branch_metric = np.zeros((4,2)) for j in range(4): branch_metric[j,0] = np.sum(np.abs(received_signal[i]-np.array([0,0,0]))**2) branch_metric[j,1] = np.sum(np.abs(received_signal[i]-np.array([1,1,1]))**2) path_metric = np.zeros((4,2)) if i == 0: path_metric[0,0] = branch_metric[0,0] path_metric[1,0] = branch_metric[2,0] path_metric[0,1] = branch_metric[0,1] path_metric[1,1] = branch_metric[2,1] else: path_metric[0,0] = branch_metric[0,0] + np.min([np.inf, path_metric[0,0], path_metric[2,1]]) path_metric[1,0] = branch_metric[2,0] + np.min([np.inf, path_metric[0,0], path_metric[2,1]]) path_metric[2,0] = branch_metric[1,0] + np.min([np.inf, path_metric[1,0], path_metric[3,1]]) path_metric[3,0] = branch_metric[3,0] + np.min([np.inf, path_metric[1,0], path_metric[3,1]]) path_metric[0,1] = branch_metric[0,1] + np.min([np.inf, path_metric[0,1], path_metric[2,0]]) path_metric[1,1] = branch_metric[2,1] + np.min([np.inf, path_metric[0,1], path_metric[2,0]]) path_metric[2,1] = branch_metric[1,1] + np.min([np.inf, path_metric[1,1], path_metric[3,0]]) path_metric[3,1] = branch_metric[3,1] + np.min([np.inf, path_metric[1,1], path_metric[3,0]]) state = np.argmin(path_metric[:,0]+path_metric[:,1]) decoded_bits = trellis[state,1:] conv_decoder[i] = decoded_bits # Calculate the Bit Error Rate (BER) ber_conv_code = np.mean(np.abs(conv_decoder-msg)) ``` By comparing the BER values for each code, we can observe that channel coding can significantly reduce the BER and improve the image quality for each SNR studied above. The Hamming Code (7,4) and the BCH Code (15,7) both have lower BER values than the uncoded transmission, while the Convolutional Code with rate 1/2 has the lowest BER value among the three codes. Therefore, channel coding is an effective way to improve the reliability and quality of the transmitted data sequence.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值