csapp ch10.3练习题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32768743/article/details/87165931

在这里插入图片描述
我猜是o,因为用的是同一个fd,但是当我写完kotlin native代码时,发现输出f

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(NativePtr.NULL)
    buffer.usePinned { pinned ->
        read(fd, pinned.addressOf(0), 1)
        println("c = ${buffer[0].toChar()}")
    }
    exit(0)
}

反直觉,我又用c写了一遍

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <zconf.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdio.h>

int main() {
    int fd;
    char c;
    fd = open("foobar.txt", O_RDONLY, 0);
    if (fork() == 0) {
        read(fd, &c, 1);
        exit(0);
    }
//    wait(NULL);
    read(fd, &c, 1);
    printf("c = %c \n", c);
    return 0;
}

输出o
在这里插入图片描述
注释掉wait,输出f
在这里插入图片描述
怀疑是kn这行代码问题,暂时还没解决

    wait(NativePtr.NULL)

书中的
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_32768743/article/details/87165931
今日推荐