我有这个c ++程序在指定的IP地址上进行简单的ping操作.我没有进入网络,所以我只是在c ++中使用system()命令从shell执行ping并将结果存储在一个文件中,这很容易.
问题是我想在执行system()命令时在屏幕上打印一些点.我尝试过:
while(system(cmd))
{
//execute the task here
}
Run Code Online (Sandbox Code Playgroud)
但没有成功.我认为我应该创建线程或东西.
你能帮助我吗 ?我应该做什么才能按照我的意愿完成这项工作?
问题system是它暂停执行直到完成.在unix系统上,您需要使用一系列fork,execv,dup2和pipe.这将允许您做一些更有用的事情.有关示例,请参见http://docs.linux.cz/programming/c/unix_examples/execill.html.
您需要使用fork像这样创建分叉进程,并使用popen从命令输出中读取输入ping google.com并相应地处理它.Beej 有一个有趣的指南,了解IPC机制,它包含在下面的代码示例中......
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int rv;
FILE *ping;
char buf[2000];
switch(pid = fork()) {
case -1:
perror("fork"); /* something went wrong */
exit(1); /* parent exits */
case 0:
// We're the child
ping = popen("ping google.com", "r");
if (ping != NULL){
fgets(buf, sizeof(buf), ping);
pclose(ping);
rv = 0;
}else{
perror("popen failed");
rv = -1;
}
exit(rv);
default:
// We're the parent...
wait(&rv);
}
// Now process the buffer
return 0;
}
希望这会有所帮助,最好的问候,汤姆.
| 归档时间: |
|
| 查看次数: |
1157 次 |
| 最近记录: |