1

我想在 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;
}
4

1 回答 1

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

于 2014-04-08T10:32:14.753 回答