how to correctly use fork, exec, wait

后端 未结 1 1759
余生分开走
余生分开走 2020-11-30 01:58

The shell i\'m writing needs to execute a program given to it by the user. Here\'s the very shortened simplified version of my program

int main()
{
    pid_t         


        
相关标签:
1条回答
  • 2020-11-30 02:34

    Here's a simple, readable solution:

    pid_t parent = getpid();
    pid_t pid = fork();
    
    if (pid == -1)
    {
        // error, failed to fork()
    } 
    else if (pid > 0)
    {
        int status;
        waitpid(pid, &status, 0);
    }
    else 
    {
        // we are the child
        execve(...);
        _exit(EXIT_FAILURE);   // exec never returns
    }
    

    The child can use the stored value parent if it needs to know the parent's PID (though I don't in this example). The parent simply waits for the child to finish. Effectively, the child runs "synchronously" inside the parent, and there is no parallelism. The parent can query status to see in what manner the child exited (successfully, unsuccessfully, or with a signal).

    0 讨论(0)
提交回复
热议问题