【问题标题】:Failed to execute echo command in system() in INIT in root file system在根文件系统的 INIT 中的 system() 中执行 echo 命令失败
【发布时间】:2014-06-07 11:35:25
【问题描述】:

主机:Intel pentium 4、RHEL 6

目标:ARM Cortex A9 运行 linux 和我自己的小型 rootffile 文件系统

我按照说明开发了一个最小的 initramfs 文件系统 这里:Minimalist Initramfs and Initrd

所以我的 initrmafs 只有以下内容:

1- 控制台

2-初始化

init 是具有以下代码的二进制文件:

* myinit.c
 * Build instructions:
 * ${CROSS_COMPILE}gcc -static init.c -o init
 * */

#include <stdio.h>

int
main ()
{
    printf ("\n");
    printf ("Hello world from %s!\n", __FILE__);
    while (1) { }
    return 0;
}

这适用于 linux 内核,并且在最后的日志消息中我收到一条 hello world 消息。

但我想要的是在打印 hello world 之后,echo 命令应该可以工作并执行以下操作:

echo 10 > test.txt
echo "$(cat test.txt)"

所以我做的是:

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

        int main ()
        {
           printf ("\n");
            printf ("Hello world from %s!\n", __FILE__);

system("echo 10 > test.txt");

system("echo \"$(cat test.txt)\"");

          while (1) { }
            return 0;
        }

我正在使用以下命令交叉编译我的代码:

  arm-xilinx-linux-gnueabi-gcc -static echotest.c -o init

Hello world 打印正确,但 echo 没有作为文件的内容工作,即 10 没有打印。

注意: 请注意,这次我的文件系统中有以下内容,即 initramfs:

1- 控制台

2-init(第二个程序的二进制文件)

3- test.txt(一个空文件)

4- 具有二进制 echo 的文件夹 bin

5- 具有二进制 cat 的文件夹 bin

除此之外,什么都没有。主要想法是拥有一个最小的文件系统,只有我的应用程序真正需要的东西。

我从一个正常工作的 linux 系统复制的二进制 cat 和 echo。

请帮助我正确运行上面的 echo 命令?

更新

我的最新代码在我安装 /bin 的位置:

#include <stdlib.h>
#include <sys/mount.h>
#include <errno.h>
#include <stdio.h>


void  mount_sys() {
    if (0 != mount("none", "/bin", "sysfs", 0, "")) {
     perror("there is an error in mounting \n");   /* handle error */
    }
    printf("mounting successful");
}

        int main ()
        {

mount_sys();
           printf ("\n");
            printf ("Hello world from %s!\n", __FILE__);

system("echo 10 > test.txt");

system("echo \"$(cat test.txt)\"");

          while (1) { }
            return 0;
        }

不幸的是,这也不起作用。引导日志消息中的最后两行是:

mounting successful
Hello world from echotest.c!   

【问题讨论】:

    标签: c linux


    【解决方案1】:

    system() 需要/bin/sh 可用。

    如果您想要真正的最小化,请改用fork/exec。像重定向这样的 Shell 结构将(显然)不可用。

    作为一种风格评论,始终检查系统调用是否有错误将是诊断问题的良好开端,即使没有明智的恢复方法。

    【讨论】:

    • 另外echo $(cat ...) 是巨大的useless
    • 感谢您的宝贵建议。能不能放几行代码解释一下?
    • echo $(cat ...) 正在将文本文件的内容放在控制台上。
    • 在 C 中重新实现 echocat 比您要求的最小部分 shell 重新实现要简单得多。如果你能指出你真正想要完成的事情,那将会有所帮助。反正网上到处都是fork/exec的例子。
    • 是的,但cat 也是如此。 (链接在 ATM 上已损坏,但在谷歌上搜索“无用的猫”。)
    猜你喜欢
    • 2017-11-12
    • 2020-12-18
    • 1970-01-01
    • 2011-03-12
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    相关资源
    最近更新 更多