Shared memory로 pointer를 공유하고 싶습니다.

익명 사용자의 이미지

shared memory server

#include
#include
#include
#include

#define SHMSZ 27

typedef struct
{
char *name;
int a;
} info;

main()
{
char c;
int shmid;
key_t key;
char *shm, *s;
char *temp;
info *inf;

/*
* We'll name our shared memory segment
* "5678".
*/
key = 5678;

/*
* Create the segment.
*/
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}

/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}

/*
* Now put some things into the memory for the
* other process to read.
*/
inf = (info *) shm;

temp = malloc(100);
strcpy(temp, "song");
inf->name = temp;

(*inf).a = 10;

printf("name address is %d\n", (*inf).name);
printf("inf name %s inf.a is %d\n", inf->name, inf->a);
/*
* Finally, we wait until the other process
* changes the first character of our memory
* to '*', indicating that it has read what
* we put there.
*/
while (1)
sleep(1);

exit(0);
}

Shared memory client

/*
* shm-client - client program to demonstrate shared memory.
*/
#include
#include
#include
#include

#define SHMSZ 27

typedef struct
{
char * name;
int a;
} info;

main()
{
int shmid;
key_t key;
char *shm, *s;
info *inf;

/*
* We need to get the segment named
* "5678", created by the server.
*/
key = 5678;

/*
* Locate the segment.
*/
if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
perror("shmget");
exit(1);
}

/*
* Now we attach the segment to our data space.
*/
if ((inf = (info *)shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}

/*
* Now read what the server put in the memory.
*/

puts("...ahahaah");
printf("inf nama addr is %d\n", inf->name);
printf("inf.name %s, info.a %d\n", inf->name, inf->a);

/*
* Finally, change the first character of the
* segment to '*', indicating we have read
* the segment.
*/

exit(0);
}

OUTPUT
server
name address is 134519184
inf name song inf.a is 10
client
inf nama addr is 134519184
inf.name , info.a 10

결국 제가 하고 싶은 것은, name과 같이 가변적인 string을 Pointer로 변
환하여 shared memory의 공간을 절약하고 싶은 것입니다.

그런데 결과는 같은 address를 가지고 있는데도 불구하고 name의 내용은
전혀 엉뚱하다는 것입니다.

결국은 같은 주소를 저장하더라도 다른 프로세스에서는 그 주소를 사용할
수 없다는 것인데...

왜 다른 프로세스는 같은 주소라 하더라도 각자 다른 내용을 가지고 있으
며, 어떻게 하면 shared memory에 Pointer를 사용할 수 있는 것인지를 알
고 싶습니다.

고수의 한말씀을 기대합니다.

익명 사용자의 이미지


기본적으로 불가능하다는 것을 알려드리고 싶군요.
결론은 안됩니다.

이유
공유메모리는 프로세스의 외부에 그 메모리가 존재합니다.
그러나 malloc은 프로세스 내부에 존재하는 머모리 입니다.

즉 공유메모리를 attech한다는 것은 잠시 자신의 힙공간으로
매핑을 해서 마치 자신(process)의 메모리인양 사용하는 것입니다.
때문에 공유메모리를 attech한 모든 프로세스의 힙 공간으로 매핑
되어 메모리를 공유하는 것입니다.

해결책
그러나 자신이 작성한 mymalloc(예) 같은 함수로 공유 메모리에서
alloc/free를 한다면 문제는 달라 지겠죠.
이때 사용할수 있는 방법은 2가지 정도 존재합니다.

1. 프로그램에서 상대적인 메모리로 pointer들을 관리 하는 방법.
-> 이 방법은 프로그램에서 명시적으로 address를 정하는 것이
아니라 항상 계산에 의해 메모리의 위치를 결정 합니다.
단점 프로그램이 복잡해진다.
pointer들을 유지 관리하는데 비용이 많이든다.
(속도가 느리다)
장점 각각의 프로그램 할당 메모리에 영향을 덜 받는다.
즉 항상 base + 상대 Address이기 때문에 각 프로그램의
attech된 address에 영향을 받지 않는다.
2. 프로그램에서 사용하는 번지를 그냥 사용한다.
-> 이 방법은 모든 프로그램이 동일한 메모리 번지를 attech하게
하여 그 번지를 직접적으로 사용한다.
단점 모든 프로그램이 항상 동일한 번지에 할당 받게 충분한
공간을 남기고 attech해야 한다.
장점 모든 프로그램이 단순해진다.
malloc에서 받은 메모리처럼 사용하면 된다.
속도가 빠르다.

익명 사용자의 이미지

고맙습니다.

처음부터 님께서 지적하신 말씀, 즉 일반적으로는 Shared memory에서 Poin
ter를 이용하여 자료를 "전혀 관계없는 Process"들 간에 공유한다는 것이
불가능 할 것이라는 것 정도는 알고 있었습니다.

그래서..혹시 다른 방법이 있는지 알아보려고 질문을 올렸던 것인데, 님
의 대답이 대단히 도움이 많이 되었습니다.

그런데 불행하게도 님의 말씀하신 myalloc이라는 함수의 두가지 구현에
대하여 개념적으로는 이해하면서도 실제로 그것을 구현하려 하는 경우에
어떻게 해야 할지 막막하기만 합니다.

혹시 그에 관련된 소스를 가지고 계시면 보내주셨으면 하고, 만약 그렇지
않다면 레퍼런스 싸이트를 알려주신다면 고맙겠습니다.

번번히 도움을 받아 깊이 감사드립니다. ^^;

익명 사용자의 이미지


libc의 malloc부분을 참조 하심이 좋겠
습니다.

bsd의 malloc 함수가 구현이 잘 되어 있으니

그쪽을 참조하는게 좋을 듯 합니다.

free bsd를 에 보면
"/usr/src/lib/libc/stdlib/malloc.c"

를 보면 되겠네요.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.