簡體   English   中英

如何在C中使用exec多次運行ping

[英]How to use exec in c to run ping multiple times

我正在嘗試制作一個簡單的腳本來理解如何使用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;
}

關於:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM