在问这个问题之前,我阅读了很多帖子,不幸的是,他们都没有为我的问题提供所需的解决方案。我正在用 gnu c 编写一个 mpi 程序,并尝试在前一个子进程中执行 hping3。实际状态是,我可以生成一个孩子,也许执行 hping3 命令,但孩子的管道输出给我以下错误消息,可能来自 hping3:
"you must specify only one target host at a time"
我做了以下事情:首先我创建了大量的字符数组来填充我的参数。为什么是数组?我想在运行时更改端口和 ip(迭代循环)
//Parameter list for hping3 fork, maxlength precalculated (tcp restrictions and given params for hping)
char sudo[] = "/usr/bin/sudo";
char path[] = "/usr/sbin/hping3";
char scan[] = "--scan";
char port[] = "65535";
char ip[] = "192.168.111.111";
char verbose[] = "-V";
char *params[7];
params[0]=sudo;
params[1]=path;
params[2]=scan;
params[3]=port;
params[4]=ip;
params[5]=verbose;
params[6]=NULL;
参数更改如下所示:
sprintf(*(params + 3), "%u", *(portarray+i));
sprintf(*(params + 4), "%u.%u.%u.%u", (iterator & 0xFF000000)>>24, (iterator & 0x00FF0000)>>16, (iterator & 0x0000FF00)>>8, (iterator & 0x000000FF));
最后是叉子。
if(pid == -1){
perror("Error forking");
} else if(pid > 0){
//Parent does not write
close(pipes[1]);
//Status Message
printf("Pipe Output ...");
fflush(stdout);
//Parent, wait for child
//waitpid(pid, &status, 0);
//Save stdout from pipe
while((nbytes = read(pipes[0], buffer+count, buffsize-count)) != -1) count+=nbytes;
//Print out pipe
printf("hping3: (%.*s)\n", nbytes, buffer);
fflush(stdout);
wait(NULL);
close(pipes[0]);
} else {
//Child does not read
close(pipes[0]);
//Map stdout and stderr to write pipe-end
dup2(pipes[1], STDOUT_FILENO);
//dup2(pipes[1], STDERR_FILENO);
//Status Message
printf("Try to execute hping3 ...");
fflush(stdout);
//Child, exec hping with params
execv("/usr/sbin/hping3",params);
puts("never happens");
close(pipes[1]);
exit(1);
}
感谢您的帮助,我有点陷入这个问题,现在已经解决了 12 个小时。