execl() 在参数中使用整数 (ping)

execl() using an integer in arguments (ping)

我一直在尝试使用 fork() 为一个父进程创建两个子进程,然后 运行 为这两个子进程创建两个 'different' 命令。我正在尝试使用这些子进程 ping 两个不同的网站。问题是当第一个 ping 'command' 被执行时它并没有结束,我尝试通过传递 -c amount 来限制输出量来解决这个问题,但由于某种原因它没有完成这项工作。这是代码:

    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;

来自 execl 文档:

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

所以你需要更换

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

例如

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

因为您没有将文件名作为第一个参数,所以它被替换为“-c5”,并且您在没有该选项的情况下执行 ping

另请注意文档:

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.


请注意,您可以使用 popen 来执行 ping 并获取它产生的输出消息