关于在Unix中实现系统功能的困惑

里克

system来自APUE的Unix功能的实现

图8.22system无需信号处理功能

#include    <sys/wait.h>
#include    <errno.h>
#include    <unistd.h>

int
system(const char *cmdstring)   /* version without signal handling */
{
    pid_t   pid;
    int     status;

    if (cmdstring == NULL)
        return(1);      /* always a command processor with UNIX */

    if ((pid = fork()) < 0) {
        status = -1;    /* probably out of processes */
    } else if (pid == 0) {              /* child */
        execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
        _exit(127);     /* execl error */
    } else {                            /* parent */
        while (waitpid(pid, &status, 0) < 0) {
            if (errno != EINTR) {
                status = -1; /* error other than EINTR from waitpid() */
                break;
            }
        }

        // if(waitpid(pid, &status, 0) < 0){
        //     if(errno != EINTR){
        //         status = -1;
        //     }
        // } 
    }

    return(status);
}

为什么使用while循环waitpid而不是if在注释中添加语句?我尝试过,if到目前为止没有发现任何错误。

dbush

除了子进程结束以外,waitpid如果函数被信号中断,则该函数可能会提前返回。如果确实如此,if则不会输入块,而是waitpid会再次尝试。

没有循环,如果waitpid被中断,您最终将处于父进程不等待子进程的状态,而当子进程退出时,您将陷入僵尸进程。直到父进程退出,该僵尸才会被清除,这时init进程成为父进程并自动等待僵尸。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章