execl in child process works for only in specific cases

时间:2015-10-06 08:23:33

标签: c++ bash pipe fork execl

I have been bussy for the last five hours with this problem so I hope someone can help me out. In my C++ program (which I develop in QTcreator on lubuntu) I want to run airodump-ng in the child process of my program. The output of airodump-ng should be directed to the STDOUT of the parent proces. This works with many other programs but strangly enough not with airodump-ng. There is simply no output in the console. This, or my Linux crashes, I get logged out and when I log back in all my programs are closed. Does anybody know why?

#include <QCoreApplication>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <sys/wait.h>

using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //execl("/usr/sbin/airodump-ng", "airodump-ng", (char*)0 );
    //dup2(1, 2); //pipe stderr to stdout

    pid_t pidAirodump;
    pid_t pidAircrack;
    int pip[2];

    if (pipe(pip) < 0) {
        perror("allocating pipe for child input redirect");
        return -1;
      }

    pidAirodump = fork();
    if(pidAirodump > 0)//parent
    {
        pidAircrack = fork();
        if(pidAircrack == 0)//pidAircrack
        {
            close(pip[0]);
            dup2(pip[1], 2);
            cout << "test" << endl;

            //execl("/usr/sbin/arp", "arp", (char*)0 );
             execl("/usr/sbin/airodump-ng", "airodump-ng ", "mon0", (char*)0 );
            exit(0);
        }
    }
    else//pidAirodump
    {
        exit(0);
    }
    wait(NULL);
    return a.exec();
}

1 个答案:

答案 0 :(得分:0)

你的计划中有一些奇怪之处。但是,让我们从问题开始 - 你应该区分execl不工作,你尝试执行的程序行为不端。如果没有特殊的权限,你不应该从用户空间程序崩溃linux。您发布的代码段不应该这样做(airpodump-ng做的是另一个问题)。

如果execl失败,它将返回并设置errno,我建议您在execl之后检查,而不仅仅是exit

现在为了奇怪:

第一个fork?你为什么那样做?你基本上是forkexit孩子。您再次fork并让父母wait - 这应该触发第一个孩子立即终止的事实。

pipe,如果您不遵守标准,为什么要这样做?相反,你dup标准错误到管道的写端,但你似乎没有对读端做任何事情。