Created
January 28, 2025 17:30
-
-
Save glennswest/140fe6436e750538fddab39a18857dae to your computer and use it in GitHub Desktop.
Check file descriptors in goland to avoid gocrash
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
package main | |
import ( | |
"fmt" | |
"os" | |
) | |
func main() { | |
// Check if standard output is open | |
if os.Stdout == nil { | |
fmt.Println("Standard output is closed.") | |
// Reopen standard output (e.g., to /dev/null) | |
f, err := os.OpenFile("/dev/null", os.O_WRONLY, 0644) | |
if err != nil { | |
panic(err) | |
} | |
os.Stdout = f | |
} | |
// Check if standard input is open | |
if os.Stdin == nil { | |
fmt.Println("Standard input is closed.") | |
// Reopen standard input (e.g., from /dev/null) | |
f, err := os.OpenFile("/dev/null", os.O_RDONLY, 0644) | |
if err != nil { | |
panic(err) | |
} | |
os.Stdin = f | |
} | |
// Check if standard error is open | |
if os.Stderr == nil { | |
fmt.Println("Standard error is closed.") | |
// Reopen standard error (e.g., to /dev/null) | |
f, err := os.OpenFile("/dev/null", os.O_WRONLY, 0644) | |
if err != nil { | |
panic(err) | |
} | |
os.Stderr = f | |
} | |
// Now you can safely use os.Stdout, os.Stdin, and os.Stderr | |
fmt.Println("Hello, world!") // This will print to standard output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment