Chdir、Setuid和Setgid是否线程安全?

huangapple go评论85阅读模式
英文:

Are Chdir and Setuid and Setgid thread safe?

问题

os.Chdiros.Setuidos.Setgid在Go语言中是线程安全的吗?

换句话说,如果我在两个并行运行的goroutine中分别调用os.Chdir(或其他两个函数),它会为工作的goroutine改变目录,还是整个进程(可能会引起问题)?

我在文档中找不到相关信息。

英文:

Are os. Chdir, os.Setuid and os.Setgid thread-safe in Go?

In otherwords, if I do a os.Chdir (or the other two functions) in two different goroutines running in parallel, is it going change directory for the working goroutine or the whole process (which can cause problems)?

I couldn't find any information in the documentation.

答案1

得分: 6

在底层,os.Chdir只是调用了chdir()系统调用:

   211	func Chdir(dir string) error {
   212		if e := syscall.Chdir(dir); e != nil {
   213			return &PathError{"chdir", dir, e}
   214		}
   215		return nil
   216	}

因此,它会影响整个进程。os.Setuidos.Setgid也是如此。

可能可以安全地同时从多个goroutine调用它们,因为执行系统调用会暂停调度器;但要注意竞态条件。

英文:

Under the hood, os.Chdir just calls the chdir() system call:

   211	func Chdir(dir string) error {
   212		if e := syscall.Chdir(dir); e != nil {
   213			return &PathError{"chdir", dir, e}
   214		}
   215		return nil
   216	}

So it affects the entire process. The same is true for os.Setuid and os.Setgid.

It is probably safe to call these from multiple goroutines at the same time, because executing a system call halts the scheduler; but beware of race conditions.

huangapple
  • 本文由 发表于 2014年4月20日 16:23:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/23180000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定