首页 > 解决方案 > 为什么我不能使用 printk() 将字符串打印到控制台

问题描述

我正在尝试将自己制作的一些系统界面添加到Linux-0.11并使用bochs调试界面。但是我发现了两个奇怪的事情。这是我的代码。

#include <errno.h>
#include <asm/segment.h>
char msg[24] = {0};//23 characters + ’\0' = 24
int sys_iam(const char* name)
/***
 * function : put the content in name(address) to msg, and the length of it should be no longer than 23  
 * return:the number of character which is copied
 ***/
{
    printk("Sys_iam is running\n");
    int i;
    //store the data temporarily
    char buf[25] = {0};
    for(i = 0;i<25;i++){
        buf[i] = get_fs_byte(name + i);
        if(buf[i] == '\0')break;
    }
    int len = i;
    //if the length is bigger than 23
    if(len > 23){
        errno = EINVAL;
        return -1;//set the errno to ENIVAL,return -1
    }
    //int j;
    int j;
    for(j = 0;j<len;j++){
        msg[j] = buf[j];
    }
    msg[len] = '\0';
    printk("len:%d\n", len);
    //printk("buflen:%d\n",strlen(buf));
    printk("buf:%s\n", buf);
    printk("msglen:%d\n",strlen(msg));
    printk("msg:%s\n", msg);
    return len;
}

我发现 msg 的 len 为 0,并且 buf 和 msg 无法在控制台上显示。 没有 strlen(buf) 的控制台截图

但是当我添加代码"printk("buflen:%s",strlen(buf));"时,我发现msglen是5,在控制台上可以看到buf,但是buf还是看不到msg。这是代码(我只添加了一行):

#include <errno.h>
#include <asm/segment.h>
char msg[24] = {0};//23 characters + ’\0' = 24
int sys_iam(const char* name)
/***
 * function : put the content in name(address) to msg, and the length of it should be no longer than 23  
 * return:the number of character which is copied
 ***/
{
    printk("Sys_iam is running\n");
    int i;
    //store the data temporarily
    char buf[25] = {0};
    for(i = 0;i<25;i++){
        buf[i] = get_fs_byte(name + i);
        if(buf[i] == '\0')break;
    }
    int len = i;
    //if the length is bigger than 23
    if(len > 23){
        errno = EINVAL;
        return -1;//set the errno to ENIVAL,return -1
    }
    //int j;
    int j;
    for(j = 0;j<len;j++){
        msg[j] = buf[j];
    }
    msg[len] = '\0';
    printk("len:%d\n", len);
    printk("buflen:%d\n",strlen(buf));
    printk("buf:%s\n", buf);
    printk("msglen:%d\n",strlen(msg));
    printk("msg:%s\n", msg);
    return len;
}

这是控制台上的内容:

使用 strlen(buf) 的控制台截图

所以我对这两件事感到困惑:

1.为什么我在控制台看不到msg

2.为什么当我添加 strlen(buf) 时 msg len 为 5(即 argv 1的 len)

这是测试代码iam.c:

#define __LIBRARY__
#include <unistd.h>
#include <stdio.h>

_syscall1(int, iam, const char*, name);
int main(int argc,char ** argv)
{
    iam(argv[1]);
    return 0;
} 

衷心感谢您的帮助!

标签: clinux-kerneloperating-system

解决方案


推荐阅读