kotlin native 調用linux c wait函數

wait(null)

這麼寫是不行的
點進去
看到要傳一個CValue的類型

public fun wait(__stat_loc: kotlinx.cinterop.CValue<platform.posix.__WAIT_STATUS>): platform.posix.__pid_t /* = kotlin.Int */ { /* compiled code */ }

還有一個類叫wait

public final class wait public constructor(rawPtr: kotlinx.cinterop.NativePtr /* = kotlin.native.internal.NativePtr */) : kotlinx.cinterop.CStructVar {
    public companion object : kotlinx.cinterop.CStructVar.Type {
    }

    public final val __wait_stopped: platform.posix.anonymousStruct21 /* compiled code */

    public final val __wait_terminated: platform.posix.anonymousStruct20 /* compiled code */

    public final var w_status: kotlin.Int /* compiled code */
}

我在 csapp ch10.3練習題 遇到的問題
代碼中wait是這樣寫的

wait(NativePtr.NULL)

調到了類的構造函數
一個可以調用的寫法是

    wait(cValue())

有沒有副作用目前還不清楚,因爲wait還牽涉到一個類

public final class __WAIT_STATUS public constructor(rawPtr: kotlinx.cinterop.NativePtr /* = kotlin.native.internal.NativePtr */) : kotlinx.cinterop.CStructVar {
    public companion object : kotlinx.cinterop.CStructVar.Type {
    }

    public final var __iptr: kotlinx.cinterop.CPointer<kotlinx.cinterop.IntVar /* = kotlinx.cinterop.IntVarOf<kotlin.Int> */>? /* compiled code */

    public final var __uptr: kotlinx.cinterop.CPointer<platform.posix.wait>? /* compiled code */
}

而且c函數是
在這裏插入圖片描述
最後輸出正確結果的代碼

package csapp

import kotlinx.cinterop.*
import platform.posix.*
import kotlin.native.internal.NativePtr

fun main() {
    val fd = open("foobar.txt", O_RDONLY, 0)
    val buffer = ByteArray(1024)
    if (fork() == 0) {
        buffer.usePinned { pinned ->
            read(fd, pinned.addressOf(0), 1)
            exit(0)
        }
    }

    wait(cValue())
    buffer.usePinned { pinned ->
        read(fd, pinned.addressOf(0), 1)
        println("c = ${buffer[0].toChar()}")
    }
    exit(0)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章