親緣進程、非親緣進程-共享內存與信號

親緣進程 共享內存與信號

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

char *share_memory = NULL;

void print() {
    printf("<parent> : %s\n", share_memory);
}

int main() {
    pid_t pid;
    int shmid;
    key_t key = ftok(".", 198);
    
    if ((shmid = shmget(key, 4096, IPC_CREAT | 0666)) < 0) {
        perror("shmget");
        return 1;
    }
    
    if ((share_memory = shmat(shmid, NULL, 0)) < 0) {
        perror("");
        return 1;
    }

    if ((pid = fork()) < 0) {
        perror("fork");
        return 1;
    }

    if (pid == 0) {
        while (1) {
            printf("<child> : ");
            scanf("%[^\n]s", share_memory);
            getchar();
            kill(getppid(), SIGUSR2);
        }
    }
    else {
        while (1) {
            signal(SIGUSR2, print);
        }
    }

    return 0;
}

非親緣進程 共享內存與信號

client

#include<sys/shm.h>  
#include<sys/ipc.h>  
#include<stdio.h>  
#include<stdlib.h>  
#include<unistd.h>  
#include<signal.h>  
#include<sys/types.h>  
#include<sys/stat.h>  
#include<string.h>  
#include<errno.h>  

struct Msg {
    int pid;
    char buff[100];
};

struct Msg *share_memory = NULL;

int main() {
    int shmid;
    char buf[50];
    pid_t pid = getpid();
    key_t key = ftok(".", 198);

    if ((shmid = shmget(key, 4096, IPC_CREAT | 0666)) < 0) {
        perror("shmget");
        return 1;
    }

    if ((share_memory = shmat(shmid, NULL, 0)) < 0) {
        perror("");
        return 1;                    
    }
   
    pid = share_memory->pid;
    
    while (1) {
        printf("<1>:");
        scanf("%[^\n]s", share_memory->buff);
        getchar();
        kill(pid, SIGUSR2);
    }
    return 0;
}

server

#include<sys/shm.h>  
#include<sys/ipc.h>  
#include<stdio.h>  
#include<stdlib.h>  
#include<unistd.h>  
#include<signal.h>  
#include<sys/types.h>  
#include<sys/stat.h>  
#include<string.h>  
#include<errno.h>  

struct Msg {
    int pid;
    char buff[100];                  
};

struct Msg *share_memory = NULL;


void print() {
    printf("<2>:%s\n", share_memory->buff);
}

int main() {
    int shmid;
    pid_t pid = getpid();
    key_t key = ftok(".", 198);
    

    if ((shmid = shmget(key, 4096, IPC_CREAT | 0666)) < 0) {
        perror("shmget");
        return 1;
    }
     
    if ((share_memory = shmat(shmid, NULL, 0)) < 0) {
        perror("");
        return 1;                    
    }
   
    share_memory->pid = pid;

    while (1) {
        signal(SIGUSR2, print);
    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章