用于选择执行bash命令的编程语言

时间:2015-10-27 13:29:07

标签: c++ linux bash output

对于我的学校项目,我必须制作一个C ++程序。该程序必须使用Linux OS上已安装的应用程序。为了熟悉从C ++应用程序中管理其他进程,我想制作一个程序,将wlan接口设置为监控模式。到目前为止我写的代码很长,看起来效率不高。有没有办法让我的代码更紧凑和有效?在程序结束时,我想执行iwconfig来检查wlan是否真的处于监控模式。最好的方法是什么?

#include <unistd.h>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main(int argc, char *argv[])
{
    string wlan = "wlan1";
    pid_t ifconfigDown;
    ifconfigDown = fork();
    if(ifconfigDown == 0)//ifconfig
    {
        execl("/sbin/ifconfig", "ifconfig", wlan.c_str(), "down",(char*)0 );
    }
    else //parent
    {
        usleep(500000);
        pid_t iwconfigMode;
        iwconfigMode = fork();
        if(iwconfigMode == 0)//ifconfig
        {
            execl("/sbin/iwconfig","iwconfig",wlan.c_str(),"mode","monitor",(char*)0 );
        }
        else//parent
        {
            usleep(500000);
            pid_t ifconfigUp;
            ifconfigUp = fork();
            if(ifconfigUp == 0)//ifconfig
            {
                execl("/sbin/ifconfig", "ifconfig", wlan.c_str(), "up", (char*)0 );
            }
            else//parent
            {
                usleep(500000);
                pid_t iwconfig;
                iwconfig = fork();
                if(iwconfig == 0)//iwconfig
                {
                    execl("/sbin/iwconfig", "iwconfig", (char*)0 );
                    //check if wlan1 is in monitor mode
                }
            }
        }
        waitpid(-1, NULL, 0);
        return 0;
    }
}


    string rPopenEnd (string cmd)
    {
         FILE *fp = popen(cmd.c_str(), "r");
        if (fp == NULL)
        {
            return "ERROR";
        }
        else
        {
            uint16_t line_size = 20;
            char line[line_size];
            string result;
            while (fgets(line, line_size, fp))
                 result += line;

            wait(NULL);
            return result;
        }
}

int main(int argc, char *argv[])
{
    rPopenEnd("iwconfig");
}

0 个答案:

没有答案
相关问题