티스토리 뷰

P rogramming/L inux

shared memory 예제

Only I Can 2012. 9. 12. 14:45
// counter.c   공유 메모리를 생성하고 공유 메모리에
// 카운터 문자열을 계속 갱신하여 넣습니다.

#include <stdio.h>      // printf()
#include <unistd.h>     // sleep()
#include <sys/ipc.h>
#include <sys/shm.h>

#define  KEY_NUM     9527
#define  MEM_SIZE    1024

int main( void)
{
   int   shm_id;
   void *shm_addr;
   int   count;

   if ( -1 == ( shm_id = shmget( (key_t)KEY_NUM, MEM_SIZE, IPC_CREAT¦0666)))
   {
      printf( "공유 메모리 생성 실패\n");
      return -1;
   }

   if ( ( void *)-1 == ( shm_addr = shmat( shm_id, ( void *)0, 0)))
   {
      printf( "공유 메모리 첨부 실패\n");
      return -1;
   }

   count = 0;
   while( 1 )
   {
      sprintf( (char *)shm_addr, "%d", count++);       // 공유 메모리에 카운터 출력
      sleep( 1);
   }
   return 0;
}

// show_counter.c   counter.c가 공유 메모리에 넣는
// 카운터 문자열을 화면에 계속 출력합니다.

#include <stdio.h>      // printf()
#include <unistd.h>     // sleep()
#include <sys/ipc.h>
#include <sys/shm.h>

#define  KEY_NUM     9527
#define  MEM_SIZE    1024

int main( void)
{
   int   shm_id;
   void *shm_addr;

   if ( -1 == ( shm_id = shmget( (key_t)KEY_NUM, MEM_SIZE, IPC_CREAT¦0666)))
   {
      printf( "공유 메모리 생성 실패\n");
      return -1;
   }

   if ( ( void *)-1 == ( shm_addr = shmat( shm_id, ( void *)0, 0)))
   {
      printf( "공유 메모리 첨부 실패\n");
      return -1;
   }

   while( 1 )
   {
      printf( "%s\n", (char *)shm_addr);    // 공유 메모리를 화면에 출력
      sleep( 1);
   }
   return 0;
}
]$ gcc counter.c -o counter          
]$ gcc show_counter.c -o show_counter
]$ ./counter &
[1] 8077
]$ ./show_counter
2
3
4
5
6
7
8

'P rogramming > L inux' 카테고리의 다른 글

tar 압축 해제  (0) 2012.09.12
shared memory 예제  (0) 2012.09.12
Linux] find grep 동시에 쓰기  (0) 2012.09.04
Linux] 디렉토리 복사, cp  (0) 2012.08.01
vi 명령어, 문자열 치환  (0) 2012.07.26
PNR 옵션  (0) 2012.07.25
D opt 사용하기  (0) 2012.07.25
댓글
댓글쓰기 폼