Find the answer to your Linux question:
Results 1 to 3 of 3
I am a new Linux engineer. Can someone tell me the difference between exec and fork. I have been reading books, but if someone can explain from their experience, it ...
  1. #1
    Just Joined!
    Join Date
    May 2009
    Posts
    11

    exec and fork in linux

    I am a new Linux engineer.

    Can someone tell me the difference between exec and fork. I have been reading books, but if someone can explain from their experience, it will really help me.

  2. #2
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    When you call exec() or use the exec command in command line, the current process is substituted with a new one. You can try in command line.

    If you run "exec gimp", bash will be closed, and the gimp process will substitute the bash session from where you are launching gimp. When you close the gimp, the xterm will be close automatically since there's no shell on it now.

    On the contrary, if you use fork (just run gimp), you will be back to the shell once you close gimp. A new process is spawned separate from bash so the shell will still be there when you close the forked process. Also, in this case, the pid of the parent process in gimp will be the pid of the shell you used to launch it.

    You can check the relevant man pages as well:

    Code:
    man 3 fork
    man 3 exec

  3. #3
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,970
    Quote Originally Posted by blackfin_dsp_uclinux View Post
    I am a new Linux engineer.

    Can someone tell me the difference between exec and fork. I have been reading books, but if someone can explain from their experience, it will really help me.
    Are you talking about shell-level programming (see first reply), or C programming? In any case, the answer is similar. Fork splits a process and duplicates its current environment, memory, file descriptors (stdin, stdout, stderr, etc), and execution stack. Exec starts a new process, in place of the current one, terminating the current process as the new one starts. Typically, in C or C++ programs, the most prevalent usage is fork() + exec() to start a new process, but enable the starting process to continue afterward. When you execute a process from a shell, such as bash, the shell does a fork() + exec() to start the new application. If it starts the application in the background (with the &) then it continues to take user input. If it doesn't start the application in the background, then it waits for the new process to terminate first.
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...