Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Process.exec(), зависает а почему ? 
V
    Опции темы
KOp4iK
Дата 3.6.2006, 23:29 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 118
Регистрация: 26.11.2004
Где: Латвия

Репутация: 1
Всего: 3



Всем добрый день!
Есть код
Код

        Runtime runtime = Runtime.getRuntime();
        Process p = runtime.exec(s);

        p.waitFor();


s = "javac c:/aaa/server/pjkt/ParseException.java"

в системной переменной прописан путь к компилеру - всё ок если запускать из командной строки. А вот из явы smile  - зависаем на p.waitFor(); т.е. не полностью зависаем - комп работает, но вот программа дальше не исполняется. А файлик то обыкновенный - сгенерированый (правда не мной  smile )
Код

/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
/**
 * Describes the input token stream.
 */

public class Token {

  /**
   * An integer that describes the kind of this token.  This numbering
   * system is determined by JavaCCParser, and a table of these numbers is
   * stored in the file ...Constants.java.
   */
  public int kind;

  /**
   * beginLine and beginColumn describe the position of the first character
   * of this token; endLine and endColumn describe the position of the
   * last character of this token.
   */
  public int beginLine, beginColumn, endLine, endColumn;

  /**
   * The string image of the token.
   */
  public String image;

  /**
   * A reference to the next regular (non-special) token from the input
   * stream.  If this is the last token from the input stream, or if the
   * token manager has not read tokens beyond this one, this field is
   * set to null.  This is true only if this token is also a regular
   * token.  Otherwise, see below for a description of the contents of
   * this field.
   */
  public Token next;

  /**
   * This field is used to access special tokens that occur prior to this
   * token, but after the immediately preceding regular (non-special) token.
   * If there are no such special tokens, this field is set to null.
   * When there are more than one such special token, this field refers
   * to the last of these special tokens, which in turn refers to the next
   * previous special token through its specialToken field, and so on
   * until the first special token (whose specialToken field is null).
   * The next fields of special tokens refer to other special tokens that
   * immediately follow it (without an intervening regular token).  If there
   * is no such token, this field is null.
   */
  public Token specialToken;

  /**
   * Returns the image.
   */
  public String toString()
  {
     return image;
  }

  /**
   * Returns a new Token object, by default. However, if you want, you
   * can create and return subclass objects based on the value of ofKind.
   * Simply add the cases to the switch for all those special cases.
   * For example, if you have a subclass of Token called IDToken that
   * you want to create if ofKind is ID, simlpy add something like :
   *
   *    case MyParserConstants.ID : return new IDToken();
   *
   * to the following switch statement. Then you can cast matchedToken
   * variable to the appropriate type and use it in your lexical actions.
   */
  public static final Token newToken(int ofKind)
  {
     switch(ofKind)
     {
       default : return new Token();
     }
  }

}


при чём у меня жуткая подозряна что проблемма даже не в самом Process"е а в том что его как-то по хитрому надо запускать... толи в отдельном потоке толи с приорететом высоким...

В общем у кого какие мысли? 
PM MAIL   Вверх
KOp4iK
Дата 3.6.2006, 23:49 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 118
Регистрация: 26.11.2004
Где: Латвия

Репутация: 1
Всего: 3



PM MAIL   Вверх
LSD
Дата 4.6.2006, 11:42 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Leprechaun Software Developer
****


Профиль
Группа: Модератор
Сообщений: 15719
Регистрация: 24.3.2004
Где: Dublin

Репутация: 210
Всего: 538



Цитата(KOp4iK @  4.6.2006,  00:29 Найти цитируемый пост)
В общем у кого какие мысли?

1. Думаю что надо заглядывать в FAQ.
2. Пользоваться поиском по форуму.
3. Не забывать про кнопку Пометить вопрос как решённый. 


--------------------
Disclaimer: this post contains explicit depictions of personal opinion. So, if it sounds sarcastic, don't take it seriously. If it sounds dangerous, do not try this at home or at all. And if it offends you, just don't read it.
PM MAIL WWW   Вверх
KOp4iK
Дата 4.6.2006, 17:37 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 118
Регистрация: 26.11.2004
Где: Латвия

Репутация: 1
Всего: 3



Цитата

Цитата(KOp4iK @  4.6.2006,  00:29 ) 
В общем у кого какие мысли? 


1. Думаю что надо заглядывать в FAQ.
2. Пользоваться поиском по форуму.
3. Не забывать про кнопку Пометить вопрос как решённый.


В фак заглядывал, поис запустил (по Process) но "неасилил" smile, я уже на столько не уверен в javac (который я собственно и пытался запустить) что решил проверить всё!

чё придумал:
Код

        Runtime runtime = Runtime.getRuntime();
        Process p = runtime.exec("javac ");

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        String str;

        System.out.println("Here is the output of the command (if any):");
        while (((str = stdError.readLine()) != null) || ((str = stdInput.readLine()) != null)) {
            System.out.println(str);
        }

        stdInput.close();
        stdError.close();
 
PM MAIL   Вверх
LSD
Дата 4.6.2006, 18:00 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Leprechaun Software Developer
****


Профиль
Группа: Модератор
Сообщений: 15719
Регистрация: 24.3.2004
Где: Dublin

Репутация: 210
Всего: 538



С этим кодом могут быть проблемы. Дело в том, что метод BufferedReader.readLine() блокируется до тех пор, пока в буффер не поступит строка полностью (т.е. с символом возврата каретки) или не будет достигнут конец потока. Если ты запускаешь приложение которое ничего не пишет в ErrorStream, но активно пишет в OutputStream, то оно встанет. Используй неблокируемое чтение:
Код
char[] buffer = new char[1024];
int read;
while(((read = stdError.read(buffer)) != -1) || ((read = stdInput.read(buffer)) != -1))
  System.out.println(new String(buffer, 0, read));


И еще, ErrorStream и OutputStream закрывать не надо. Не ты их открывал, не тебе их и закрывать. 


--------------------
Disclaimer: this post contains explicit depictions of personal opinion. So, if it sounds sarcastic, don't take it seriously. If it sounds dangerous, do not try this at home or at all. And if it offends you, just don't read it.
PM MAIL WWW   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.1055 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.