about fork and execve system call

前端 未结 5 1718
难免孤独
难免孤独 2021-02-02 18:11

It is said that fork system call creates a clone of the calling process, and then (usually) the child process issues execve system call to change its i

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 19:01

    The reason for the two-step is flexibility. Between the two steps you can modify the context of the child process that the newly exec'ed program will inherit.

    Some things you may want to change are:

    • File descriptors
    • User/group ID
    • Process group and session IDs
    • Current directory
    • Resource limits
    • Scheduling priority and affinity
    • File creation mask (umask)

    If you did not split up fork and exec and instead had a single spawn-like system call, it would need to take arguments for each of these process attributes if you wanted them set differently in a child process. For example, see the argument list to CreateProcess in the Windows API.

    With fork/exec, you change whatever inheritable process attributes you want to in the child before you exec the new program.

    Setting up file descriptors is one of the more common things to change in a child's process context. If you want to capture the output of a program, you will typically create a pipe in the parent with the pipe(2) system call, and after fork(2)ing, you will close the write end in the parent process and close the read end in the child process before calling execve(2). (You'll also use dup(2) to set the child end of the pipe to be file descriptor 1 (stdout)). This would either be impossible or restrictive in a single system call.

提交回复
热议问题