WSL1 ubuntu 20.04 有關sleep系統調用不能正常工作的問題

遇到了一個很奇怪的問題,在WIN10的WSL1(ubuntu 20.04)上,sleep、nanosleep系統調用總會立即返回,而且沒有任何提示信息。同時shell命令的sleep也不能正常使用,會出現如下錯誤信息:

$ sleep 1
sleep: cannot read realtime clock: Invalid argument

在另一臺機子上測試確實不是代碼的問題。後來在網上找到原因:Ubuntu 20.04 and WSL 1.

[WSL1] [glibc] sleep: cannot read realtime clock: Invalid argument #4898

Issue 4989

An example of the WSL team continuing to service WSL 1 for now is a patch for issue 4989 231. Issue 4989 arises from a patch in glibc 2.31 34 that implements a nanosleep() library call in a more UNIX-like manner 23 based on CLOCK_REALTIME. Emulating UNIX system clocks on an NT kernel is tricky. WSL 1 implemented the most popular clock-based system calls, but not all of them, and did not build CLOCK_REALTIME support into nanosleep 5. But because this is such a fundamental change in glibc the WSL team is very graciously implementing support for CLOCK_REALTIME in nanosleep in WSL 1 and will be backporting it in updates to existing builds. This is a challenging task that will take some time. In contrast, other more obscure system clock calls, like the one raised in issue 4973 73, will likely not see implementation in WSL 1.

大意就是說在NT系統上模擬UNIX的 REALTIME比較麻煩,修復這個問題需要不少時間, 目前官方的建議是使用 Ubuntu 18.04版本。

看來是解決不了了,只能棄用了。我就想着用用新版本趕趕潮流,沒想到會遇上這種問題🙃。


我還是不能拒絕船新版本的誘惑,經過了幾小時的探(搜)索,目前找到了一個比較滿意的解決方案:使用WSL2!!
安裝方法可以參考官方網站

大概步驟如下:

  1. 更新到WIN10 2004(操作系統版本號19041)及以上版本。(真是太及時了,2020.05.28 剛剛發佈,截止到目前我沒有收到更新推送,但是還好可以手動更新);
  2. 依次打開:“控制面板” - “程序和功能” - “啓用或關閉Windows功能” - 勾選上 “適用於Linux的Windows子系統” 和 “虛擬機平臺” 這兩個選項。確認,然後重啓。
  3. 以管理員身份打開 Powershell命令行,執行

$ wsl --list --verbose # 查看當前 wsl 狀態,可以看到已有的WSL1的名字
$ wsl --set-default-version 2 # 設置默認 WSL 體系結構爲 WSL2。這個可有可無,只對以後新安裝的 WSL有效。
$ wsl --set-version <WSL1的名字> 2 # 將指定的 WSL1 升級爲WSL2。

執行wsl --set-version時可能會提示需要更新WSL2 linux內核,就按它提示的網站下載安裝即可。
4. 完成。

WSL2 實現是用的hyper-v虛擬機,對 Liinux 系統調用及硬件的控制幾乎完全兼容。試了一下果然沒讓我失望, sleep 的問題得到完美解決。

換用WSL2後,一個意外地收穫是編譯速度快了不少,真香😋

2020/06/01 15:42
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章