Skip to content

Commit

Permalink
fixed example for macOS
Browse files Browse the repository at this point in the history
  • Loading branch information
Code-Hex committed Aug 29, 2022
1 parent 09db4f3 commit 2a17b22
Showing 1 changed file with 40 additions and 22 deletions.
62 changes: 40 additions & 22 deletions example/macOS/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import (
"fmt"
"log"
"os"
"os/signal"
"runtime"
"syscall"
"time"

"github.com/Code-Hex/vz/v2"
)
Expand Down Expand Up @@ -48,9 +47,6 @@ func runVM(ctx context.Context) error {
}
vm := vz.NewVirtualMachine(config)

signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGTERM)

errCh := make(chan error, 1)

vm.Start(func(err error) {
Expand All @@ -59,28 +55,50 @@ func runVM(ctx context.Context) error {
}
})

vm.StartGraphicApplication(960, 600)
go func() {
for {
select {
case newState := <-vm.StateChangedNotify():
if newState == vz.VirtualMachineStateRunning {
log.Println("start VM is running")
}
if newState == vz.VirtualMachineStateStopped || newState == vz.VirtualMachineStateStopping {
log.Println("stopped state")
errCh <- nil
return
}
case err := <-errCh:
errCh <- fmt.Errorf("failed to start vm: %w", err)
return
}
}
}()

for {
select {
case <-signalCh:
// cleanup is this function is useful when finished graphic application.
cleanup := func() {
for i := 1; vm.CanRequestStop(); i++ {
result, err := vm.RequestStop()
if err != nil {
return err
}
log.Println("recieved signal", result)
case newState := <-vm.StateChangedNotify():
if newState == vz.VirtualMachineStateRunning {
log.Println("start VM is running")
}
if newState == vz.VirtualMachineStateStopped {
log.Println("stopped successfully")
return nil
log.Printf("sent stop request(%d): %t, %v", i, result, err)
time.Sleep(time.Second * 3)
if i > 3 {
log.Println("call stop")
vm.Stop(func(err error) {
if err != nil {
log.Println("stop with error", err)
}
})
}
case err := <-errCh:
return fmt.Errorf("failed to start vm: %w", err)
}
log.Println("finished cleanup")
}

runtime.LockOSThread()
vm.StartGraphicApplication(960, 600)
runtime.UnlockOSThread()

cleanup()

return <-errCh
}

func computeCPUCount() uint {
Expand Down

0 comments on commit 2a17b22

Please sign in to comment.