如何管理hping3从孩子到父母的输出?

时间:2014-11-28 14:03:03

标签: c pipe exec fork output-redirect

我最近问了一个关于如何在c程序中调用hping3的问题。 提供的解决方案有效,但我现在有另一个问题。必须将hping3的输出传递给父进程,因此我执行了以下操作。 请注意,这只是代码片段,我认为错误在其中。 以下片段在循环内部运行,其中我遍历一系列ip地址,这对于在我的mpi程序中提供两种不同的分发策略是必要的。

//Stick together the params
sprintf(params, "--scan %u %u.%u.%u.%u -V", *(portarray + i), (iterator & 0xFF000000)>>24, (iterator & 0x00FF0000)>>16, (iterator & 0x0000FF00)>>8, (iterator & 0x000000FF));
            //Pipe and check status
            if(pipe(pipes)==-1){
               perror("Error piping");
            }
            //Fork and check status
            pid=fork();
            if(pid == -1){
               perror("Error forking");
            } else if(pid > 0){
               //Parent does not write
               close(pipes[1]);
               //Save stdout from pipe
               nbytes = read(pipes[0], buffer, sizeof(buffer));
               //Parent, wait for child
               waitpid(pid, &status, 0);
               //Print out pipe
               printf("hping3: (%.*s)\n", nbytes, buffer);
               wait(NULL);
               close(pipes[0]);
            } else {
               //Child does not read
               close(pipes[0]);
               //Map stdout and stderr to write pipe-end
               dup2(pipes[1], 1);
               dup2(pipes[1], 2);
               //Child, exec hping with params
               execl("sudo /usr/sbin/hping3","sudo /usr/sbin/hping3",params,NULL);
               close(pipes[1]);
               //Exit child to prevent fork-bomb
               return 0;
            }
            //Sleep for specified delaytime
            sleep((unsigned int)delay);

我无法找出问题所在。 输出如下(当然是循环中):

hping3()

hping3程序打印到stdout和stderr,我通过输出重定向到文件在shell上测试它。

1 个答案:

答案 0 :(得分:1)

如何定义缓冲区?你有没有检查过nbytes的值?你确定正在执行hping吗?我尝试使用以下内容:

int buffsize  = 100;
char * buffer = malloc(buffsize);

if (pid == -1) {
   perror("Error forking");
} else if (pid > 0) {
   //Parent does not write
   close(pipes[1]);
   // I'd first wait for the child to finish.
   waitpid(pid, &status, 0);
   // Save stdout from pipe 
   // recall that sizeof(buffer) != buffsize when malloc'ed.
   int count = 0;
   while((nbytes = read(pipes[0], buffer+count, buffsize-count) != -1) count += nbytes;
   //Print out pipe
   printf("hping3: (%.*s)\n", nbytes, buffer);
   wait(NULL);
   close(pipes[0]);
} else {
   //Child does not read
   close(pipes[0]);
   //Map stdout and stderr to write pipe-end
   dup2(pipes[1],1);
   dup2(pipes[1],2);
   // Close pipes[1]
   close(pipes[1]);
   //Child, exec hping with params
   if (execl("sudo /usr/sbin/hping3","sudo /usr/sbin/hping3",params,NULL) == -1)
      perror("execl error");
   //Exit child to prevent fork-bomb
   return 0;
}