在System V共享内存段中写入

时间:2014-04-11 03:10:44

标签: c linux shared-memory

我正在研究共享内存,现在我正在编写一个使用系统v共享内存的程序。这是我的代码:

#include    <stdlib.h>
#include    <stdio.h>
#include    <unistd.h>
#include    <string.h>
#include    <sys/wait.h>
#include    <sys/shm.h>
#include    <sys/ipc.h>
#include    <fcntl.h>

#define PG_SIZE sysconf(_SC_PAGESIZE)
#define PROJ_ID 1
#define SHM_FILE "/dev/shm/myshm"

void executeChild( void );
void executeParent( void );

int main ( int argc, char *argv[] )
{
    unlink(SHM_FILE);
    int fd = creat(SHM_FILE, S_IRWXU );
    if( fd == -1 ){
        perror("Segment memory file creation failed");
        exit(1);
    }
    int pid = fork();
    if( pid < 0){
        perror("Fork failed\n");
        return EXIT_FAILURE;
    }
    if( pid ){
        executeParent();
        printf("Parent waiting...\n");
        int status = 0;
        wait(&status); //wait for child process
        printf("Parent done\n");

    }else{
        executeChild();
    }
    close( fd );
    return EXIT_SUCCESS;
}               

void executeChild( void )
{
    printf("Child running\n");
    sleep(15);
}    

void executeParent( void )
{
    printf("Parent running\n");
    key_t token = ftok(SHM_FILE, PROJ_ID);
    if( token == -1 ){
        perror("Token creation failed");
        exit(1);
    }
    int segment = shmget( token, PG_SIZE, IPC_CREAT | IPC_EXCL | S_IRWXU);
    if ( segment == -1 ){
        perror("Segment creation failed");
        exit(1);
    }
    void * shm_ptr =  shmat(segment, NULL, 0);
    if( shm_ptr == (void *)(-1) ){
        perror("Segment attachament failed");
        exit(1);
    }
    printf("Shared memory ( %d ) attached\n", segment);
    struct shmid_ds shm_info;
    if( shmctl(segment, IPC_STAT, &shm_info) == -1 ){
        perror("shmctl failed");
        exit(1);
    }
    printf("Segment size = %zu\n", shm_info.shm_segsz);
    printf("Writing...\n");
    const char * test = "teste";
    memcpy(shm_ptr, test, strlen(teste));
}

创建共享内存的文件。我可以在/ dev / shm上看到它,icps commando也会显示它。但是我的共享内存段的文件大小没有增加。因此,我认为memcpy不像我预期的那样正常工作。为什么呢?

1 个答案:

答案 0 :(得分:0)

最后,我知道共享内存真的有用......特别感谢Thiago Klock。 传递给ftok的文件不会改变其大小。它仅用于生成进程间通信中使用的唯一键...:)

这是我的源代码,我的父进程将一条简单的消息写入子进程:

https://github.com/guilhermesft/vanzstuff/blob/master/ipc/shmsysv.c

相关问题