Приложение Qt GUI неожиданно завершает работу - PullRequest
1 голос
/ 14 марта 2012

Привет! Я работаю в Linux и пытаюсь создать приложение с графическим интерфейсом, которое бы соответствовало выполненному мной исполняемому файлу.

По какой-то причине оно неожиданно заканчивается.Нет сообщения об ошибке, просто в окне консоли Qt он неожиданно завершился с кодом выхода 0.

Может кто-нибудь, пожалуйста, посмотрите на меня.Я работаю в Linux.

Я также вставлю сюда код.

void MainWindow::on_pushButton_clicked()
{
    QString stringURL = ui->lineEdit->text();

    ui->labelError->clear();
    if(stringURL.isEmpty() || stringURL.isNull()) {
        ui->labelError->setText("You have not entered a URL.");
        stringURL.clear();
        return;
    }

    std::string cppString = stringURL.toStdString();
    const char* cString = cppString.c_str();

    char* output;

    //These arrays will hold the file id of each end of two pipes
    int fidOut[2];
    int fidIn[2];

    //Create two uni-directional pipes
    int p1 = pipe(fidOut);                //populates the array fidOut with read/write fid
    int p2 = pipe(fidIn);                 //populates the array fidIn  with read/write fid
    if ((p1 == -1) || (p2 == -1)) {
        printf("Error\n");
        return;
    }

    //To make this more readable - I'm going to copy each fileid
    //into a semantically more meaningful name
    int parentRead  = fidIn[0];
    int parentWrite = fidOut[1];
    int childRead   = fidOut[0];
    int childWrite  = fidIn[1];

    //////////////////////////
    //Fork into two processes/
    //////////////////////////
    pid_t processId = fork();

    //Which process am I?
    if (processId == 0) {
        /////////////////////////////////////////////////
        //CHILD PROCESS - inherits file id's from parent/
        /////////////////////////////////////////////////
        ::close(parentRead);      //Don't need these
        ::close(parentWrite);     //

        //Map stdin and stdout to pipes
        dup2(childRead,  STDIN_FILENO);
        dup2(childWrite, STDOUT_FILENO);

        //Exec - turn child into sort (and inherit file id's)
        execlp("htmlstrip", "htmlstrip", "-n", NULL);

    } else {
        /////////////////
        //PARENT PROCESS/
        /////////////////
        ::close(childRead);       //Don't need this
        ::close(childWrite);      //

        //Write data to child process
        //char strMessage[] = cString;
        write(parentWrite, cString, strlen(cString));
        ::close(parentWrite);     //this will send an EOF and prompt sort to run

        //Read data back from child
        char charIn;
        while ( read(parentRead, &charIn, 1) > 0 ) {
            output = output + (charIn);
            printf("%s", output);
        }
        ::close(parentRead);      //This will prompt the child process to quit
    }

    return;
}

РЕДАКТИРОВАТЬ :: ОТЧЕТЫ ОТЛАДКИ

Я запустил отладчик, и это ошибкаполучил:

The inferior stopped because it received a signal from the Operating System.

Signal name : SIGSEGV
Signal meaning : Segmentation fault

1 Ответ

5 голосов
/ 14 марта 2012

Вы не инициализировали переменную «output». В последних строках вашего кода вы делаете это:

while ( read(parentRead, &charIn, 1) > 0 ) {
    output = output + (charIn);
    printf("%s", output);
}

Что будет плохо, поскольку вы добавляете чтение байта из вашего дочернего процесса в выходную переменную, которая является указателем, содержащим мусор, и затем печатаете содержимое адреса выходной переменной в виде строки. Вы, вероятно, хотите, чтобы «output» был std::string, чтобы ваш код мог иметь смысл:

std::string output;
/* ... */
while ( read(parentRead, &charIn, 1) > 0 ) {
    output += (charIn);
}
std::cout << output;

Как только вы прочитаете все данные, сгенерированные вашим дочерним процессом, вы можете записать их в стандартный вывод.

EDIT : поскольку вы хотите установить содержимое «output» в QPlainTextEdit, вы можете использовать QPlainTextEdit :: setPlainText:

while ( read(parentRead, &charIn, 1) > 0 ) {
    output += (charIn);
}
plainTextEdit.setPlainText(output.c_str());
...