c - 如何在c中使用exec多次运行ping

标签 c g++ exec ping

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

#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;
}

最佳答案

关于:

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;
    }
}

关于c - 如何在c中使用exec多次运行ping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54778648/

相关文章:

c - 我是否以错误的方式使用结构?

c - C 中的隐式函数声明

c - Readline.H 在 C 中的历史用法

c - 如何返回一个指向完整数组的指针,也就是 int(*)[] 到主函数

c++ - 如何在 C++ 中正确定义模板的流运算符

c - 使用 NULL 强制结束可变函数参数

c++ - std::vector::push_back 不可复制对象给出编译器错误

c++ - 在没有文件的情况下编译 C++ 代码

go - 在 Golang 中将字符串通过管道传输到命令的 STDIN

客户端与服务器通信,执行命令