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

问题描述 投票:0回答:1

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

#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;
}
c g++ exec ping
1个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.