哪一个选择waitpid / wait / waitid?

时间:2014-04-08 09:53:46

标签: c linux fork wait waitpid

我想在fork之后在子进程中使用execl。 execl将执行大约120秒的脚本。我尝试了几乎所有与waitpid的组合,wait和waitid与不同的参数(0,WNOHANG等),但在所有情况下我得到-1返回值。所以我想知道我需要在哪个等待函数使用?所以我可以专注于一个等待功能来使它工作。

我从日志中观察到的另一个有趣的事情是,当我在子进程中什么也不做时,它将我的父线程显示为孤立的。我不知道怎么可能?我的父线程怎么会变成孤儿?

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

int main(void)
{
    pid_t Checksum_pid = fork();

    if (Checksum_pid < 0)
        printf("Fork Failed\n");
    else if (Checksum_pid == 0)
    {
        execl("/bin/ls","ls",(char *)NULL) ;
        exit(EXIT_FAILURE);
    }
    else
    {
        int childStatus;
        pid_t returnValue = waitpid(Checksum_pid, &childStatus, 0);

        if (returnValue > 0)
        {
            if (WIFEXITED(childStatus))
                printf("Exit Code: %d\n", WEXITSTATUS(childStatus));

        }
        else if (returnValue == 0)
            printf("Child process still running\n");
        else
        {
            if (errno == ECHILD)
                printf(" Error ECHILD!!\n");
            else if (errno == EINTR)
                printf(" Error EINTR!!\n");
            else
                printf("Error EINVAL!!\n");
        }
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

正如我评论的那样:你的上一个else应该只是

 else perror("waitpid");

但是你得到了ECHILD。所以请阅读waitpid(2)手册页:

   ECHILD (for wait()) The calling process does not have any unwaited-
          for children.

  ECHILD (for waitpid() or waitid()) The process specified by pid
          (waitpid()) or idtype and id (waitid()) does not exist or is
          not a child of the calling process.  (This can happen for
          one's own child if the action for SIGCHLD is set to SIG_IGN.
          See also the Linux Notes section about threads.)
顺便说一句,我无法重现你的错误。检查ulimit -a对bash的限制。

也许你的execl失败了(特别是如果你执行了一些脚本而不是/bin/ls)。在其之后添加对perror的调用。

此外,使用gcc -Wall -g进行编译并使用stracegdb

相关问题