搜档网
当前位置:搜档网 › QT下执行Shell或启动外部程序

QT下执行Shell或启动外部程序

QT下执行Shell 或启动外部程序

方案一:
调用linux C函数库中的int system(const char * string);应该能够实现你需要的功能
system( command )
特定指令被执行并且如果它返回一个1的退出值,那么这个作用域中的设置将会被处理。例如:

system( ls /bin ) {
SOURCES += bin/main.cpp
HEADERS += bin/main.h
}
所以如果命令ls /bin返回1,那么bin/main.cpp将被添加到源文件列表中并且bin/main.h将被添加到头文件列表中。

你是说LINUX里面的CONSOLE窗口?
fork之后,在子进程里用exec来执行一个相关程序就可以了。程序名不记得了,自己看一下就知道了。

这样就可以运行一个shell程序
char * args [2] = { "/bin/sh", NULL };
execv (args [0], args);

如果要弹出的话,用fork或system

if (fork () == 0) {
execv (args [0], args);
exit(1);
}

system(args[0]);

system("/etc/rc.d/init.d/leds stop");




方案二:

使用QProcess启用外部程序


因为目前的程序需要提供一个文件对比的功能,而目前已经有专门的文本对比软件,所以我打算直接调用外部的文本对比程序。
通过查阅QT的帮助文档,发现了QProcess这个类可以提供这种需求。
我找到的启动外部程序的方法有以下两种:
1、start()

void QProcess::start ( const QString & program, const QStringList & arguments, OpenMode mode = ReadWrite )
Starts the program program in a new process, passing the command line arguments in arguments. The OpenMode is set to mode. QProcess will immediately enter the Starting state. If the process starts successfully,QProcess will emit started(); otherwise, error() will be emitted.

Note that arguments that contain spaces are not passed to the process as separate arguments.

Windows: Arguments that contain spaces are wrapped in quotes.

Note: Processes are started asynchronously, which means the started() and error() signals may be delayed. Call waitForStarted() to make sure the process has started (or has failed to start) and those signals have been emitted.

See also pid(), started(), and waitForStarted().


2、使用QProcess::execute(), 不过使用此方法时程序会最阻塞直到此方法执行的程序结束后返回,这时候可使用QProcess和QThread这两个类结合使用的方法来处理,以防止在主 线程中调用而导致阻塞的情况
先从QThread继承一个类,重新实现run()函数:

Quote:
class MyThread : public QThread
{
public:
void run();
};

void MyThread::run()
{
QProcess::execute("notepad.exe");
}

这样,在使用的时候则可定义一个MyThread类型的成员变量,使用时调用其start()方法:

Quote:
class ...............
{...........
MyThread thread;
............
};

.....................
thread.s

tart();

两个的具体的区别我不是很清楚,但我在程序中分别试了下,发现第二个会阻塞主程序,但使用start()则不会。下面是我使用QProcess启动WinMerge的代码。
#include
QProcess *process = new QProcess;
QStringList str;
str << "";
process->start("./WinMerge/WinMergeU.exe",str);
如果程序里面不输入参数,就会直接到软件直接运行时的界面。
加参数后弹出的界面是工具栏第一列中的第一个需要输入的界面(这个是我猜测的,不确定,但确实能弹出)。

嗯,这样就可以启动外部程序了。

补充:在主程序退出时,启动的外部程序是不会随着主程序的退出而退出的,我们当然不希望这种情况。
继续查阅QT帮助文档,发现close这个函数,看下它的说明:

void QProcess::close () [virtual]
Closes all communication with the process and kills it. After calling this function, QProcess will no longer emit readyRead(), and data can no longer be read or written.

Reimplemented from QIODevice.

可以看到,调用这个后会关闭所有的process启动的外部程序。因此,可以在主程序推出前,加一个判断

if(process)

process->close();

delete process;

process = 0;


相关主题