简体   繁体   中英

Ubuntu Shared Memory Between 2 Processes, Code Not Working

I'm writing two processes separately which should interact through shared memory and I just can't spot where I'm going wrong. The first process has definitely created the shared memory and if reprogrammed, it can read from shared memory too.

However, the second Output program can't seem to read from it at all. I use shmget in both programs to create a memory, then to join it. I insert the char array nameArray with the Input program, then the Output should read it from shared memory and cout the name.

Any help is appreciated, code is below :)

Input:

#include <iostream>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#define SHM_KEY 982
using namespace std;

main()
{
    int shmid;
    char nameArray[] = "Bill Gates";
    unsigned length = sizeof(nameArray)/sizeof(nameArray[0]);
    shmid=shmget(SHM_KEY,256,0777|IPC_CREAT);

    if(shmid!=(-1))     /*Error checking measure to ensure shared memory creation was successful*/
    {
        char * ptr=(char *)shmat(shmid,0,0);    /*Assigns the char pointer to the start of shared memory*/

        for(int i=0; i<length;i++)      /*For every letter in the nameArray*/
        {
            ptr=(char *)shmat(shmid,0,i);
            *ptr=nameArray[i];      /*Sends the local char array to shared memory*/
        }
    }
    else    /*Displays Error message given shared memory creation failue*/
    {
        cout << "Sorry, shared memory creation failed"
    }
}       

Output:

#include <iostream>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#define SHM_KEY 982
using namespace std;

main()
{
    int shmid;
    char nameArray[20];
    shmid=shmget(SHM_KEY,256,0777|IPC_CREAT);

    if(shmid!=(-1)) /*Error checking measure to ensure shared memory creation was successful*/
    {
        char * ptr=(char *)shmat(shmid,0,0);

        for(int i=0; i<11;i++)
        {
            cout << *((char *)shmat(shmid,0,i));
        }

    }
    else{}
}       

The code

    for(int i=0; i<length;i++)      /*For every letter in the nameArray*/
    {
        ptr=(char *)shmat(shmid,0,i);
        *ptr=nameArray[i];      /*Sends the local char array to shared memory*/
    }

is not doing what you think it is doing. Every call to shmat attaches the whole shared memory segment to another address, with different flags (ranging from 0 to length ; most of them meaningless).

Remove shmat calls from the loop. What you really need is

    for(int i=0; i<length;i++)      /*For every letter in the nameArray*/
    {
        ptr[i]=nameArray[i];      /*Sends the local char array to shared memory*/
    }

and a similar change in the other program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM