/
00_os.go
118 lines (102 loc) · 2.1 KB
/
00_os.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"fmt"
"os"
"os/user"
"time"
)
func main() {
fmt.Println("TempDir:", os.TempDir())
pwd, err := os.Getwd()
if err != nil {
panic(err)
}
// get the current user
usr, err := user.Current()
if err != nil {
panic(err)
}
homePath := usr.HomeDir
// change the directory
if err := os.Chdir(homePath); err != nil {
panic(err)
}
// get current working directory
if twd, err := os.Getwd(); err != nil {
panic(err)
} else {
fmt.Println("home pwd:", twd)
}
// home pwd: /home/ubuntu
if err := os.Chdir(pwd); err != nil {
panic(err)
}
// get current working directory
if twd, err := os.Getwd(); err != nil {
panic(err)
} else {
fmt.Println("home pwd:", twd)
}
fpath := "temp.txt"
// this errors for non-existing file.
if err := os.Remove(fpath); err != nil {
// panic(err)
fmt.Println(err)
}
// this errors for non-existing file.
file, err := os.Open(fpath)
if err != nil {
// panic(err)
fmt.Println(err)
// open temp.txt: no such file or directory
// THIS DOES NOT GET CALLED
// BECAUSE the process will be killed
// in the next lines
defer func() {
fmt.Println("Deleting", fpath)
if err := os.Remove(fpath); err != nil {
// panic(err)
fmt.Println(err)
}
}()
fmt.Println("Creating", fpath)
file, err = os.Create(fpath)
if err != nil {
panic(err)
}
fmt.Println(file)
}
fmt.Println("Deleting", fpath)
if err := os.Remove(fpath); err != nil {
// panic(err)
fmt.Println(err)
}
// get process id
pid := os.Getppid()
fmt.Println("pid:", pid)
// find the process
p, err := os.FindProcess(pid)
if err != nil {
panic(err)
}
go func() {
fmt.Println("goroutine: killing the process in 1 second...")
time.Sleep(time.Second)
if err := p.Kill(); err != nil {
panic(err)
}
}()
fmt.Println("Sleeping 1,000 hours in main function...")
time.Sleep(1000 * time.Hour)
}
/*
remove temp.txt: no such file or directory
open temp.txt: no such file or directory
Creating temp.txt
&{0xc8200164b0}
Deleting temp.txt
pid: 16635
Sleeping 1,000 hours in main function...
goroutine: killing the process in 1 second...
Killed
*/