github.com/tristanisham/sys@v0.0.0-20240326010300-a16cbabb7555/unix/sysvshm_unix_test.go (about)

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build (darwin && amd64) || linux
     6  
     7  package unix_test
     8  
     9  import (
    10  	"runtime"
    11  	"testing"
    12  
    13  	"golang.org/x/sys/unix"
    14  )
    15  
    16  func TestSysvSharedMemory(t *testing.T) {
    17  	// create ipc
    18  	id, err := unix.SysvShmGet(unix.IPC_PRIVATE, 1024, unix.IPC_CREAT|unix.IPC_EXCL|0o600)
    19  
    20  	// ipc isn't implemented on android, should fail
    21  	if runtime.GOOS == "android" {
    22  		if err != unix.ENOSYS {
    23  			t.Fatalf("expected android to fail, but it didn't")
    24  		}
    25  		return
    26  	}
    27  
    28  	// The kernel may have been built without System V IPC support.
    29  	if err == unix.ENOSYS {
    30  		t.Skip("shmget not supported")
    31  	}
    32  
    33  	if err != nil {
    34  		t.Fatalf("SysvShmGet: %v", err)
    35  	}
    36  	defer func() {
    37  		_, err := unix.SysvShmCtl(id, unix.IPC_RMID, nil)
    38  		if err != nil {
    39  			t.Errorf("Remove failed: %v", err)
    40  		}
    41  	}()
    42  
    43  	// attach
    44  	b1, err := unix.SysvShmAttach(id, 0, 0)
    45  	if err != nil {
    46  		t.Fatalf("Attach: %v", err)
    47  	}
    48  
    49  	if len(b1) != 1024 {
    50  		t.Fatalf("b1 len = %v, want 1024", len(b1))
    51  	}
    52  
    53  	b1[42] = 'x'
    54  
    55  	// attach again
    56  	b2, err := unix.SysvShmAttach(id, 0, 0)
    57  	if err != nil {
    58  		t.Fatalf("Attach: %v", err)
    59  	}
    60  
    61  	if len(b2) != 1024 {
    62  		t.Fatalf("b2 len = %v, want 1024", len(b1))
    63  	}
    64  
    65  	b2[43] = 'y'
    66  	if b2[42] != 'x' || b1[43] != 'y' {
    67  		t.Fatalf("shared memory isn't shared")
    68  	}
    69  
    70  	// detach
    71  	if err = unix.SysvShmDetach(b2); err != nil {
    72  		t.Fatalf("Detach: %v", err)
    73  	}
    74  
    75  	if b1[42] != 'x' || b1[43] != 'y' {
    76  		t.Fatalf("shared memory was invalidated")
    77  	}
    78  }