本文介绍了Linux fork()和wait()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个难闻的气味:(

i have one, bad smelling problem :(

我有这个代码:

int main()
{
    pid_t child, parent;
    int status=0;
    int i;

    printf("parent = %d\n", getpid());

    for(i=1; i<=5; i++){
        if( (child = fork()) == 0){
            sleep(i);
            printf("i=%d, %d\n",i, getpid());
        }
    }
    wait(0);
    while( (parent = wait(&status)) > 0){
        printf("Exit = %d, child = %d\n", status/256, parent);
    }
}

,输出类似于:

    1, 21320
    2, 21321
    Exit = 0, child = 21321
    3, 21322
    Exit = 0, child = 21322
    4, 21323
    Exit = 0, child = 21323
    5, 21324
    Exit = 0, child = 21324

我认为wait(0)不等待所有子进程,而仅等待第一次退出并全部写入(Exit = ...).

And i think that wait(0) not waiting for all subprocess but only wait for first exit and write all (Exit = ...).

有什么方法可以做到:

    1, 21320
    2, 21321
    3, 21322
    4, 21323
    5, 21324

    Exit = 0, child = 21320
    Exit = 0, child = 21321
    Exit = 0, child = 21322
    Exit = 0, child = 21323
    Exit = 0, child = 21324

?

推荐答案

以下是按您要求的顺序生成输出的最简单方法的演示.它使用3个循环:一个循环创建子进程,一个循环等待子进程并收集其退出状态,另一个循环打印退出状态.

Here's a demo of the easiest way to produce the output in the order you asked for. It uses 3 loops: one to create the child processes, one to wait for them and collect their exit statuses, and one to print the exit statuses.

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

#define NUMPROC 5

int main(void)
{
  pid_t child[NUMPROC];
  int status[NUMPROC];
  int i;

  printf("parent = %d\n", getpid());

  for(i=0;i<NUMPROC;++i) {
    if(fork() == 0) {
      sleep(i);
      printf("i=%d, %d\n",i, getpid());
      _exit(0);
    }
  }

  for(i=0;i<NUMPROC;++i)
    child[i] = wait(&status[i]);

  for(i=0;i<NUMPROC;++i)
    printf("Exit = %d, child = %d\n", WEXITSTATUS(status[i]), child[i]);
}

这篇关于Linux fork()和wait()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:52