多个进程写入共享内存

时间:2018-07-12 09:53:35

标签: c memory posix shared

我必须编写一个具有多个进程的程序,以将共享存储中标准输入所取的字符串写到共享内存中,而不会覆盖先前添加的字符串。当父亲收到信号时,SIGINT将打印所有放入共享内存的字符串。问题是它的表现不符合预期,有人可以帮助我吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/mman.h>

#define MAXSIZE 50

int n; 
char *at;
int *p;

void handler(int sig){

    printf("Received signal %d\n", sig);
    printf("Printinf all the data in the shared memory\n");

    printf("At1 è uguale: %d\n", n);

    while(*p != -1){

        printf("%s\n", at);
        at = at -MAXSIZE;
        *p = *p-1;
        printf("Valore di p: %d\n", *p);

    }

    exit(1);

}

int main(int argc, char **argv){

    if(argc != 2){

        fprintf(stderr, "Usage: %s numberOfProcesses\n", argv[0]);
        exit(1);

    }

    sem_t *sem;
    sem = sem_open("femaforo", O_CREAT, 0664, 1);
    if(sem == SEM_FAILED){

        perror("Error while creating semaphore\n");
        exit(-1);

    }

    n = atoi(argv[1]);

    pid_t pid, wpid;

    key_t key = 1411;
    key_t key1 = 788;

    /*int shmid = shmget(key, 1024, IPC_CREAT | 0644);
    if(shmid < 0){

        perror("Error while creating shared memory\n");
        exit(-1);

    }*/


    at = (char *)mmap(NULL, 1024, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0);
    if(at == (void *)-1){

        perror("Error while attaching memory\n");
        exit(-1);

    }
    int shmid2 = shmget(key1, sizeof(int), 0644 | IPC_CREAT);
    if(shmid2 < 0){

        perror("Error while creating second memory\n");
        exit(-1);

    }

    p = (int *)shmat(shmid2, NULL,0);
    if(p == (void *)-1){

        perror("Error while attaching second memory\n");
        exit(-1);

    }

    *p = 0;


    for(int i = 0; i < n; i++){

        pid = fork();

        if(pid == 0){

            printf("I am a process with pid: %d\n", getpid());
            break;

        }else if(pid < 0){

            perror("Error while creating a process\n");
            exit(-1);

        }


    }

    if(pid == 0){//figlio

        sem_wait(sem);

        printf("In at c'è: %s\n", at);

        char string[MAXSIZE];

        printf("Insert a string for the shared memory\n");
        scanf("%s", string);
        strcpy(at, string);

        at = at +MAXSIZE;

        *p = *p +1;

        printf("Value of p is: %d\n", *p);

        sem_post(sem);

    }else{ //padre

        sigset_t set;
        sigfillset(&set);
        sigdelset(&set, SIGINT);
        struct sigaction act;

        act.sa_mask = set;
        act.sa_handler = handler;

        sigaction(SIGINT, &act, 0);

        for(int i = 0; i < n; i++){

            wpid = wait(NULL);


        }

        handler(0);

        printf("I am the father and I am exiting\n");

        exit(1);


    }

}

0 个答案:

没有答案