0

Here is an example, ignorning the error checking:

int main()
{
    pid_t pid = fork();
    if(0 == pid)
    {
        for(int i = 0; i < 5; ++i)
        {
            char* const args[] = { "/bin/ls", nullptr };
            execve("/bin/ls", args, nullptr);
        }
    }
    else if(pid > 0)
    {
        wait(nullptr);
    }
}

If exec() after fork(), as far as I know, the linux will not copy but cover original system.

If I want to keep running execve() in for() loop like this, what should I do ?

  • 2
    Call `fork` ***in*** the loop? – Some programmer dude Apr 06 '17 at 06:37
  • What do you mean about "keep running execve in for loop"? Do you want to run multiple `/bin/ls`? – ikh Apr 06 '17 at 06:38
  • 1
    If you want to execute `ls` 5 times, you need to call `fork` 5 times. – n. m. could be an AI Apr 06 '17 at 06:40
  • Possible duplicate of [Differences between fork and exec](http://stackoverflow.com/questions/1653340/differences-between-fork-and-exec) – autistic Apr 06 '17 at 07:45
  • Other duplicate questions: [Multiple `execlp` not working](http://stackoverflow.com/questions/15188115/multiple-execlp-not-working), [Why does `execv` exit a function?](http://stackoverflow.com/questions/27773445/why-does-execv-exit-a-function), [Difference between `system` and `exec` in Linux](http://stackoverflow.com/questions/1697440/difference-between-system-and-exec-in-linux)... – autistic Apr 06 '17 at 07:54

1 Answers1

1

exec (all of the different forms) will replace your current executable with the one given to exec, so NOTHING you do within the forked code will matter. You need to either do a loop around fork, or convince the author of the other program to run the loop for you.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227