Linux -- 自启动程序的调试信息输出

自启动的程序,如果在程序使用 printf、puts 等输出函数,在终端是不会有任何输出的,那么对于程序调试阶段的一些debug信息不能直观的看到,下面几种简单的方式,可以尝试一下。

一、如果想要在终端上打印数据,并且数据量少的情况下

1、可以使用 fprintf 重定向输出即可。

#include <stdio.h>

int main(int argc, const char **argv)
{
    FILE *fs;

    fs = fopen("/dev/console", "w+");
    fprintf(fs, "debug message.\n");
    fclose(fs);
    
    return 0;
}

2、简单的调试信息,可以直接使用重定向来实现

#include <stdio.h>
#include <stdlib.h> // system

int main(int argc, const char **argv)
{
    system("echo debug message > /dev/console");
    
    return 0;
}

或者

#include <stdio.h>
#include <stdlib.h> // system

int main(int argc, const char **argv)
{
    char *p = "this is a test";
    char cmd[128] = {0};

    sprintf(cmd, "echo line = %d, buf = %s > /dev/console", __LINE__, p);
    system(cmd);

    return 0;
}

二、写入到文件中

1、针对上面这个历程,如果调试的信息比较多,那么可以将信息重定向到文件中,可直接将

sprintf(cmd, "echo line = %d, buf = %s > /dev/console", __LINE__, p);

替换成文件名称,比如 filename

sprintf(cmd, "echo line = %d, buf = %s >> filename", __LINE__, p);

注意:

>> 而不是 > ,区别就是 追加覆盖

2、其他的各种文件IO操作的函数,请自行ABCD(^_^)!

猜你喜欢

转载自blog.csdn.net/zhemingbuhao/article/details/103906945