Created
February 27, 2024 10:46
-
-
Save leveryd/9f48b6d1d441435bc9c8d61ff67ebf3c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 需要先创建文件 touch file1.txt、file2.txt、file3.txt | |
package main | |
import ( | |
"fmt" | |
"syscall" | |
"os/exec" | |
"os" | |
) | |
func main() { | |
flag := syscall.O_RDONLY // 或者其他的组合,比如 syscall.O_RDWR | syscall.O_CREATE | |
mode := uint32(0644) // 文件权限,这里是典型的读写权限 | |
// 打开两个文件 | |
_, err := syscall.Open("file1.txt", flag&^syscall.O_CLOEXEC, mode) | |
if err != nil { | |
panic(err) | |
} | |
_, err = syscall.Open("file2.txt", flag&^syscall.O_CLOEXEC, mode) | |
if err != nil { | |
panic(err) | |
} | |
file, err := os.Open("file3.txt") | |
var input string | |
fmt.Print("输入任意字符继续") | |
fmt.Scanln(&input) | |
// 执行bash的sleep命令 | |
cmd := exec.Command("bash", "-c", "sleep 50000") | |
// 将文件描述符添加到命令的 ExtraFiles 字段中 | |
cmd.ExtraFiles = []*os.File{file} | |
err = cmd.Run() | |
if err != nil { | |
fmt.Println("执行命令失败:", err) | |
return | |
} | |
// 注意:在实际编程中,我们应该在完成文件操作后关闭文件以释放资源 | |
// 但在本示例中,为了满足题目要求,我们在此处不关闭文件 | |
// defer file1.Close() | |
// defer file2.Close() | |
fmt.Println("程序结束") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment