【问题标题】:Reaping zombie process - child收割僵尸进程-孩子
【发布时间】:2010-02-28 23:12:43
【问题描述】:

我将命令行参数从父级传递到子级,并计算它们并打印。我的问题是我不确定我正在收割这个孩子吗?我不只需要一个出口 0 还是我需要再次调用 fork?

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

int main(int argc, char *argv[])
{

int length = 0;
int i, n;

int     fdest[2];          // for pipe
pid_t   pid;              //process IDs
char    buffer[BUFSIZ];


if ((pid = fork()) < 0)  /* attempt to create child / parent process */

{
    printf("fork error");
} 

if (pipe(fdest) < 0)          /* attempt to create pipe */
    printf("pipe error");

/* parent process */
else if (pid > 0) {      
    close(fdest[0]);

    for(i = 1; i < argc; i++)    /* write to pipe */
    {
        write(fdest[1], argv[i], strlen(argv[1]));
    }

} else {   

    /* child Process */
    close(fdest[1]);

    for(i = 1; i < argc; i++)
    {
        length +=( strlen(argv[i])); /* get length of arguments */
    }

    n = read(fdest[0], buffer, length);
    printf("\nchild: counted %d characters\n", n);

}
exit(0);
}

【问题讨论】:

  • 僵尸可以在C中生孩子吗?我从不学习那种语言。
  • 替换 printf("管道错误");带错误(“管道”);对于叉子也是如此。错误消息应该有用并写入标准错误。

标签: c


【解决方案1】:

不,你没有正确地收割孩子。在您的情况下,如果子进程在父进程退出之前完成,则子进程将成为僵尸。然后,当父进程完成时,子进程将被重新设置为init(无论它已经完成并且是僵尸,还是仍在运行)。 init 正在为你收割孩子。

要收割孩子,请在exit 之前添加对wait() 的调用。

顺便说一句,您还有另一个错误 - 您正在创建管道 fork,因此父子节点各自创建一个(不同的)管道 - 它们没有连接。将if (pipe(... 上移到fork() 之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 2016-07-03
    • 2014-05-09
    • 1970-01-01
    相关资源
    最近更新 更多