linux - 进程等待使用linux系统调用wait

标签 linux process fork waitpid

我正在尝试使用 fork 系统调用创建一个进程,然后等待子进程。我使用了以下内容:

waitpid (pid, &status, 0);

1)第一个问题是status向左移了8位,例如子进程返回1,waitpid函数返回status变量中status的值为256,请告知原因它正在这样做。

2)根据手册,waitpid等待子进程改变状态。但它也说:

“wait() 系统调用挂起调用进程的执行,直到 它的一个 child 终止。调用 wait(&status) 是等价的 到:

waitpid(-1, &status, 0);"

我在这里有点困惑 waitpid 和 wait 调用是等待状态改变还是等待子进程终止。请澄清这一点。

第三个参数中的零指定了什么?

3) 如果我将子进程置于 sleep 状态,子进程的状态是否会通过等待例如 5 秒而变为等待状态?

以下是我的程序:

int main(int argc, char ** argv)   
{  
pid_t pid = fork();  
pid_t ppp;  

if (pid==0)
{
    sleep(8);
    printf ("\n I am the first child and my id is %d \n", getpid());
    printf ("The first child process is now exiting now exiting\n\n");
    exit (1);
}

else {
            int status = 13;
            printf ("\nI am now waiting for the child process %d\n", pid);
            waitpid (pid, &status, 0);
            printf ("\n the status returned by the exiting child is %d\n", status>>8);
        }

printf("\nI am now exiting");
exit(0);

谢谢

最佳答案

status 参数编码的不仅仅是 child 的退出代码。来自 man waitpid:

WIFEXITED(status)
returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should only be employed if WIFEXITED returned true.

main waitpid 解释了第三个参数的作用。

The value of options is an OR of zero or more of the following constants:
WNOHANG
return immediately if no child has exited.
WUNTRACED
also return if a child has stopped (but not traced via ptrace(2)). Status for traced children which have stopped is provided even if this option is not specified.
WCONTINUED (since Linux 2.6.10)
also return if a stopped child has been resumed by delivery of SIGCONT.

状态变化的定义非常精确和狭义。来自 man waitpid:

A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal.

休眠不是状态改变。被 SIGSTOP/SIGTSTP 停止。

关于linux - 进程等待使用linux系统调用wait,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41416580/

相关文章:

linux - shell读取多余的换行符

linux - 在 ansible 剧本中添加 sudo_user 会使命令永远执行

linux - 如何运行本身启动两个后台进程的后台 shell 脚本?

python - python 中轮询套接字的问题

php - 当网站托管在centos vmware中时,无法获取$_FILE ["name"] ["tmp_name"]

c# - 在任务栏中从 C# 应用程序聚焦 Windows 资源管理器

process - Docker守护进程

创建一个不是创建它的进程的子进程

c - 程序的行为就像等待一个角色

linux - i3:窗口变量的 .config 文件错误