【问题标题】:How to use exec in c to run ping multiple times如何在c中使用exec多次运行ping
【发布时间】:2019-02-20 04:03:30
【问题描述】:

我正在尝试制作一个简单的脚本来了解如何使用 PING 命令来获得乐趣(现在正在大学学习数据安全课程)。我有以下代码:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main( void )
{
    int status;
    char *args[2];

    args[0] = "ping 192.(hidden for privacy) -s 256 ";        // first arg is the full path to the executable
    args[1] = NULL;             // list of args must be NULL terminated

    if ( fork() == 0 )
        execv( args[0], args );
    else
        wait( &status );       

    return 0;
}

【问题讨论】:

  • 该函数有三 (3) 种返回:fork() 1) 0 表示在父进程中。发布的代码无法检查失败情况
  • 那么您面临的问题是什么?请提及问题的位置和描述

标签: c g++ exec ping


【解决方案1】:

关于:

char *args[2];

args[0] = "ping 192.(hidden for privacy) -s 256 ";        
args[1] = NULL; 

不正确,程序 ping 由 shell 运行,每个字符串需要在单独的参数条目中。

建议:

int main( void )
{
    char *args[] = 
    {
        "bash",
        "-c",
        "ping",
        "190",
        "192...",  // place the IP address here
        "-s",
        "256",
        NULL
    };


    pid_t pid = fork();

    switch( pid )
    {
         case -1:
             // an error occurred
             perror( "fork failed" );
             exit( EXIT_FAILURE );
             break;

        case 0:
            // in child process
            execv( args[0], args );
            // the exec* functions never return 
            // unless unable to generate 
            // the child process
            perror( "execv failed" );
            exit( EXIT_FAILURE );
            break;

        default:
            int status;
            wait( &status );
            break;
    }
}

【讨论】:

  • 我收到四个错误:desktop.cpp:9:9: warning: conversion from string literal to 'char *' is deprecated [-Wc++11-compat-deprecated-writable-strings ] "-c", ^.
  • 然后,我收到三个错误:desktop.cpp:25:14: error: use of undeclared identifier 'perror' perror("fork failed"); ^ desktop.cpp:26:20: 错误:使用未声明的标识符“EXIT_FAILURE”退出(EXIT_FAILURE);
  • 'perror()` 原型在头文件中:stdio.hexit()' and EXIT_FAILURE`在头文件中被原型化/定义:stdlib.h
  • 关于:9:9... 的评论缺少引用实际行的回声。请发布整个错误消息
  • 我消除了大部分错误,希望您能帮助我找出当前版本的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 2023-03-06
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 2020-03-21
  • 2012-03-03
相关资源
最近更新 更多