使用共享内存实现进程与进程通信
要求:循环发送(可获取键盘输入,也可内置消息,间隔1s以上),循环接受,不落下任何消息,不输出空消息,不输出重复消息。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <strings.h>
int main(int argc, char const *argv[])
{
    key_t key = ftok("./", 1);
    int shmid = shmget(key, 256, IPC_CREAT | 0666);
    printf("%d\n", shmid);
    pid_t pid;
    int i = 0;
    for (i = 0; i < 2; i++)
    {
        pid = fork();
        if (pid < 0)
        {
            perror("fork");
            return -1;
        }
        else if (pid == 0)
        {
            break;
        }
    }
    if (i == 2)
    {
        pid_t son_pid;
        while (1)
        {
            son_pid = waitpid(-1, NULL, WNOHANG);
            if (son_pid < 0)
            {
                break;
            }
        }
    }
    else if (i == 1)
    {
        void *str = shmat(shmid, NULL, 0);
        char buf[64] = "";
        
#if 1
        //读共享内存(空不读,重复不读)
        while (1)
        {
            if (strcmp((char *)str, "") == 0)
            {
                continue;
            }
            else if (strcmp((char *)str, buf) == 0)
            {
                continue;
            }
            else
            {
                printf("%s\n", (char *)str);
                
                strcpy(buf, (char *)str);
                if (strstr((char *)str, "9"))
                {
                    shmctl(shmid, IPC_RMID, NULL);
                    break;
                }
            
            }
        }
#endif
    }
    else
    {
        //每隔1s写共享内存
        void *str = shmat(shmid, NULL, 0);
        char buf[64] = "";
        for (int n = 0; n < 10; n++)
        {
            sleep(1);
            bzero((char *)str, 256);
            bzero(buf, sizeof(buf));
            sprintf(buf, "第%d个数据", n);
            strcpy((char *)str, buf);
        }
    }
    return 0;
}










