Ejemplo n.º 1
0
int main(int argc, char **argv)
{
    pid_t pid;

    pid = fork();
    
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);        
    } else if (pid == 0) {
        // クライアント(子プロセス)
        int shmfd;
        
        // Unix ドメインクライントを作り shmfd を受信
        shmfd = do_client();

        // shmfd を使って mmap() を行い共有メモリに書き込み
        void *addr;
        addr = mmap(NULL, TEMPFILE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, shmfd, 0);
        if (addr == MAP_FAILED) {
            perror("mmap");
            exit(EXIT_FAILURE);
        }
        sprintf((char*)addr, "ABCDEFG");

        close(shmfd);        
    }  else {
        // サーバー(親プロセス)

        // 共有ファイルの file descriptor を取得
        int shmfd;
        shmfd = create_shm_file();

        // Unix ドメインサーバを作り shmfd を送信
        do_server(shmfd);

        // 子プロセスの終了を待つ
        if (waitpid(pid, NULL, 0) == -1) {
            perror("waitpid");
            exit(EXIT_FAILURE);
        }

        // shmfd を使って mmap() を行い共有メモリの内容を表示
        void *addr;
        addr = mmap(NULL, TEMPFILE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, shmfd, 0);
        if (addr == MAP_FAILED) {
            perror("mmap");
            exit(EXIT_FAILURE);
        }
        close(shmfd);

        // 子プロセスが書き込んだ内容が見えれば成功
        puts((const char*)addr);
    }

    return 0;
}
Ejemplo n.º 2
0
/* Open the shared memory segment *R_KEY and return a file descriptor
   to it in R_FD.  If KEY is IPC_PRIVATE, use a private key and return
   it in R_KEY.  */
static error_t
get_exclusive (int shmflags, size_t size, key_t *r_key, int *r_fd)
{
  error_t err;
  file_t dir;
  file_t file;
  char filename[SHM_NAMEMAX];
  key_t key = *r_key;
  bool is_private;

  /* Create the shared memory segment.  */
  err = create_shm_file (size, shmflags, &dir, &file);
  if (err)
    return err;

  if (key == IPC_PRIVATE)
    {
      is_private = true;
      key = SHM_PRIV_KEY_START;

      /* Try to link the shared memory segment into the filesystem
	 (exclusively).  Private segments have negative keys.  */
      do
	{
	  sprintf (filename, SHM_NAMEPRI, key);
	  err = __dir_link (dir, file, filename, 1);
	  if (!err)
	    {
	      /* We are done.  */
	      *r_key = key;
	      break;
	    }
	  else if (err == EEXIST)
	    {
	      /* Check if we ran out of keys.  If not, try again with new
		 key.  */
	      if (key == SHM_PRIV_KEY_END)
		err = ENOSPC;
	      else
		err = 0;

	      key--;
	    }
	}
      while (!err);
    }
  else
    {
      /* Try to link the shared memory segment into the filesystem
	 (exclusively) under the given key.  */
      sprintf (filename, SHM_NAMEPRI, key);
      err = __dir_link (dir, file, filename, 1);
    }

  __mach_port_deallocate (__mach_task_self (), dir);

  if (!err)
    {
      int fd;

      /* Get a file descriptor for that port.  */
      fd = _hurd_intern_fd (file, O_RDWR, 1); /* dealloc on error */
      if (fd < 0)
	err = errno;
      else
	*r_fd = fd;
    }

  return err;
}