Search code examples
cforkexecl

execl() using an integer in arguments (ping)


I've been attempting to create two children to one parent process using fork(), then running two 'different' commands for those two children. I'm attempting to ping two different websites with these child processes. The thing is when the first ping 'command' is executed it doesn't end, I tried solving this by passing -c amount to limit the amount of outputs, but for some reason it's not doing the job. Here's the code:

    pid = fork();
        if(pid!=0) {
          wait(&status);
          printf("----------------------------------------------------\n\n");
          printf ( " I am the parent my PID is %d, myPPID is %d, \n ",getpid(),getppid());
          printf("---------------------------------------------------\n\n");
       }else {
         printf ( " I am the child , my PID is %d , my PPID is %d \n",getpid(),getppid());
         printf("---------------------------------------------------\n\n");
         execl ( "/bin/ping","-c5", "sheffield.ac.uk",(char*)0);
         return 0;
       if(pid!=0){
         printf ( " I am the child , my PID is %d , my PPID is %d \n",getpid(),getppid());
         printf("---------------------------------------------------\n\n");

       }else {
         printf ( " I am the child , my PID is %d , my PPID is %d \n",getpid(),getppid());
         printf("---------------------------------------------------\n\n");
         sleep(2);
         execl ( "/bin/ping","-c5", "shu.ac.uk",(char*)0);
         return 0;
       }

  }
        break;

Solution

  • From execl documentation :

    The first argument, by convention, should point to the filename associated with the file being executed.

    so you need to replace

    execl ( "/bin/ping","-c5", "sheffield.ac.uk",(char*)0);
    

    by for instance

    execl ( "/bin/ping", "ping", "-c5", "sheffield.ac.uk",(char*)0);
    

    Because you don't give the filename as the first argument it is replaced by "-c5" and you do ping without that option

    Note also from the documentation :

    Return Value

    The exec() functions only return if an error has occurred. The return value is -1, and errno is set to indicate the error.


    Note you can use popen to execute your ping and also to get the output messages it produces