Как использовать exec в c для запуска ping несколько раз - PullRequest
0 голосов
/ 20 февраля 2019

Я пытаюсь сделать простой скрипт, чтобы понять, как использовать команду 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;
}

1 Ответ

0 голосов
/ 20 февраля 2019

относительно:

char *args[2];

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

неверно, программа ping запускается оболочкой, и каждая строка должна быть в отдельной записи аргумента.

Предложить:

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