无法在根文件系统的INIT中的system()中执行echo命令

时间:2014-06-07 11:35:26

标签: c linux

主机:Intel pentium 4,RHEL 6

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

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

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

1- console

2 init

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消息。

但我想要的是在打印你好世界之后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- console

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

3- test.txt(空文件)

4-具有二进制echo

的文件夹bin

5-具有二进制cat

的文件夹bin 从这些Aprt,没有什么。主要的想法是拥有一个最小的文件系统,只有我的应用程序真正需要的东西。

我从一个正在运行的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!   

1 个答案:

答案 0 :(得分:2)

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

如果您真的想要最小化,请改用fork / exec。然后(显然)不能使用像重定向这样的Shell构造。

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