Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Клуб юнуксоидов > возможно, опять баг


Автор: MAKCim 10.3.2008, 23:21
проделайте следующие шаги
1.
Код

#!/usr/bin/python

# main.py

import sys

print sys.argv

2.
Код

#include <unistd.h>

/* main.c */

int main() {
    char * argv[2] = {"string", NULL};
    execve("main.py", argv, NULL);
    return 0;
}

3. компилируем main.c и запускаем
выводится 
Цитата

['main.py']

а не
Цитата

['main.py', 'string']

ошибка (если это ошибка) в fs/binfmt_script.c
в функции load_script() зачем то идет вызов функции remove_arg_zero(), которая удаляет первый параметр командной строки
вызов настолько очевиден, что на баг это не похоже
но с другой стороны, почему такое поведение
вообщем, что думаете?

Автор: nickless 11.3.2008, 00:16
man exec пишет
Цитата(exec(3))

The functions described in this manual page are front-ends for the function execve(2).

...

The  const  char  *arg and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the  executed program.  The first argument, by convention, should point to the filename associated with the file being executed.


Пример в man 2 execve
Код

/* execve.c */

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

int
main(int argc, char *argv[])
{
    char *newargv[] = { NULL, "hello", "world", NULL };
    char *newenviron[] = { NULL };

    assert(argc == 2);  /* argv[1] identifies
                           program to exec */
    newargv[0] = argv[1];

    execve(argv[1], newargv, newenviron);
    perror("execve");   /* execve() only returns on error */
    exit(EXIT_FAILURE);
}

тоже передаёт название файла первым аргументом.

Возможно для скриптов первый аргумент просто заменяется названием файла скрипта, хотя в мане
Цитата(execve(2))
Interpreter scripts
An interpreter script is a text file that has execute permission enabled and whose first line is of the form:

#! interpreter [optional-arg]

The interpreter must be a valid pathname for an executable which is not itself a script.  If the filename argument of execve() specifies an interpreter script, then interpreter will be invoked with the following arguments:

interpreter [optional-arg] filename arg...

where arg...  is the series of words pointed to by the argv argument of execve().

про это не говорится...

Добавлено через 5 минут и 45 секунд
Я думаю так как первым параметром обычно передаётся название файла, а интерпреторы при таком использовании
Цитата(nickless @  10.3.2008,  22:16 Найти цитируемый пост)
interpreter [optional-arg] filename arg...

по той же конвенции тоже передают первым аргументом название скрипта, то первый аргумент просто удаляют, чтобы его не было 2 раза в списке аргументов.

Автор: MAKCim 11.3.2008, 11:02
nickless
то, что в man 2 execve об этом не говорится ни слова, меня и смутило
но в любом случае, я не понимаю, в чем тайный смысл передачи в качестве первого параметра командной строки фиктивного параметра
достаточно в fs/exec.c в do_execve() вместо
Код

retval = copy_strings_kernel(1, &bprm->filename, bprm);
         if (retval < 0)
                 goto out;
 
         bprm->exec = bprm->p;
         retval = copy_strings(bprm->envc, envp, bprm);
         if (retval < 0)
                 goto out;
 
         retval = copy_strings(bprm->argc, argv, bprm);
         if (retval < 0)
                 goto out;

написать
Код

         retval = copy_strings(bprm->envc, envp, bprm);
         if (retval < 0)
                 goto out;
 
         retval = copy_strings(bprm->argc, argv, bprm);
         if (retval < 0)
                 goto out;
    retval = copy_strings_kernel(1, &bprm->filename, bprm);
         if (retval < 0)
                 goto out;

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)