5

As when we do fork on current process, our process as parent process generates child process with same characteristics but different process IDs. So after that, when we do exec() in our child process, process stops execution, and our program which was executing in our stoppped child process, now has his own process.

Isn't that the same as when we run our applications in particular after which every application has his own process and PID?

2
  • "Isn't that the same as when we run our applications in particular after which every application has his own process and PID number?" ... doesn't parse. What are you trying to say?
    – muru
    Sep 24, 2015 at 9:01
  • 1
    exec() doesn't change the PID, if that's what you're asking.
    – cxw
    Sep 24, 2015 at 9:14

1 Answer 1

10

Yes, because that's how it's done in UNIX.

There is no "run application" system call; it's always done by fork/exec pairs.

Incidentally, exec does not generate a new PID. exec replaces the contents of the process -- the memory is discarded, and a whole new executable is loaded -- but the kernel state remains the same (open files, environment variables, working directory, user, etc.), and the PID remains the same.


Further reading, if you're interested:

  • vfork is like fork except that it must always be paired with exec, and is useful when fork can't work, as in ucLinux.

  • clone is the new fork (today's fork function uses clone behind the scenes) but does a lot more, including creating new processes that share the same memory (rather than duplicate it, like fork) and we call those threads.

11
  • 1
    Yes, the fork creates a new PID, and the exec inherits the new number.
    – ams
    Sep 24, 2015 at 9:35
  • 1
    I don't understand your question. Everything is a process.
    – ams
    Sep 24, 2015 at 9:39
  • 3
    Your shell process runs fork to create a new process, when you hit enter, and then the new forked process runs exec with the command you wrote.
    – ams
    Sep 24, 2015 at 9:44
  • 1
    @ams, is fork() efficient? Say I have a large application that runs a simple process /bin/ls for example to take its output. All parent's memory will be duplicated just to be replaced from ls?
    – Vassilis
    Feb 3, 2019 at 13:38
  • 3
    @Vassilis, it's not duplicated, it's shared. The only copying is a few page tables inside the kernel. If the child process attempts to write to memory, only then does the memory get duplicated, and only for that one page (about 4k, I think).
    – ams
    Feb 4, 2019 at 14:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .