Passing Linux boot opts to Init

筅森魡賤 提交于 2019-12-07 19:37:31

问题


I would like to pass some parameters to a customized Linux init via the boot options configured in the bootloader at boot.

I've written test init's in both Python and C. The Python version is able to see anything in the kernel boot options that doesn't have a '=' or '.' in it. The values are found in sys.argv. However, the C program doesn't seem to get passed the values. I would have thought the sys.argv list in Python was generated by parsing the **argv array. Below are the test scripts and screen shots that will hopefully help clarify.

the kernel boot line is:

kernel /grub/linux-2.6.38.4 root=/dev/vda1 init=/argv-{p|c} one two three four five

Python version:

#!/usr/bin/python

import sys

i = 0
print("Printing argv[] (Python) ...")
for each in range(i, len(sys.argv)):
    print("argv[%d] - %s" % (i, sys.argv[i]))
    i += 1
print("...finished printing argv[]")

C version:

#include <stdio.h>

int main(int argc, char **argv)
{
    int i;
    printf("Printing argv[] (C) ...\n");
    for(i; i < argc; i++) {
        printf("argv[%d] - %s\n", i, argv[i]);
    }
    printf("...finished printing argv[]\n");
}

You can see just before the test programs exit (and causes panic) the python version spits out the boot options the kernel didn't digest while the C version didn't. I've looked at the sysvinit source code and it looks to me (not being a C dev) that it works the same way?

How do I get the boot options passed to my C init program?

(oh, and the C program works as expected when not being run as init)


回答1:


I don't know C, but I think where is int i; (line 4) should be int i = 0;. If I am wrong, add a comment to my answer and I will delete it.

Edit: you could also do i = 0 in the for loop: for(i = 0; i < argc; i++).




回答2:


You need to initialize i to 0 as Artur said. If you dont the value of i is whatever happend to be in the memory at the time the program ran. Sometimes it will work, others i would be >= argc and the loop would be skipped, the worst case i is negative and your program segfaults.

Also in python try:

# i do not need to be initialized
# for counting xrange is better, it does not built the whole list on memory
for i in xrange(1, len(sys.argv)):
    print("arg[%d] - %s" % (i, sys.argv))
    # i do not need to be incremented manually


来源:https://stackoverflow.com/questions/5944692/passing-linux-boot-opts-to-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!