简体   繁体   中英

How to use exec in c to run ping multiple times

I am trying to make a simple script to understand how to using the PING command for fun (taking a data security class at uni right now). I have the following code:

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

regarding:

char *args[2];

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

is not correct, the program ping is run by the shell and each string needs to be in a separate argument entry.

Suggest:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM