子进程的行为异常 [英] Strange behavior with Child process

查看:90
本文介绍了子进程的行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对子进程的行为有疑问.此测试程序的目的是运行Linux命令 echo.wc 使用管道.

I have a question about the behavior of child processes. The intention of this test program is to run the Linux command echo Hello | wc using piping.

我的命令不起作用,结果是调用了错误的c字符串.

My commands were not working, and it turns out the wrong c-string is being called.

预期输出为:

command 0
echo
command 1
wc

但是,我得到了:

command 0
echo 
command 1
Hello

我只有在注释掉后才能获得预期的输出execvp(),不退出子进程时.

I only get the expected output when I comment out execvp(), when the child processes are not being exited.

这是测试功能:

int test(pid_t id[])
{
    int i;
    int pipefd[2];

    char *cat_args[] = {"echo","Hello", NULL};
    char *grep_args[] = {"wc", NULL};
    char **arr[] = {cat_args,grep_args};

    // make a pipe 
    pipe(pipefd);

    for(i = 0; i < 2; i++){
        id[i] = fork();

        if (id[i] == -1){
            printf("Unable to create child process");
            fprintf(stderr,"fork() failed to spawn child process");
            exit(1);
        }
        else if (id[i] == 0){
            printf("command ");
            printf("%d\n",i);
            
            if (i == 0){
                dup2(pipefd[0],STDIN_FILENO);
            }
            else if (i == 1){
                dup2(pipefd[1],STDOUT_FILENO);
            }
            // Close pipes for child processes
            close(pipefd[0]);
            close(pipefd[1]);

            printf("%s\n",*arr[i]);
            //To simply and simulate problem, can replace execvp() with exit(0);
            execvp(*arr[i],arr[i]);
        }
    }
    // Close pipes of parent process    close(pipefd[0]);
    close(pipefd[1]);
    return 0;
}

这是主要功能:

int main(int argc, char **argv)
{ 
    pid_t id[2];
    test(id);

    int status;
    
    waitpid(id[0],&status,0); 
    waitpid(id[1],&status,0); 
    return 0;
}

推荐答案

printf 写入stdout,因此它受您的 dup2(pipefd [1],STDOUT_FILENO); 影响>,因此进入管道,而不是显示在屏幕上.

printf writes to stdout, so it's affected by your dup2(pipefd[1],STDOUT_FILENO);, and therefore goes into the pipe instead of on your screen.

您应该将诊断消息写到stderr:

You should instead write your diagnostics messages to stderr:

fprintf(stderr, "%s\n", *arr[i]);

看到 Hello 的原因是这是反向管道的输出.

The reason why you see Hello is that this is the output of your reversed pipeline.

wc | echo Hello

如果你想显示 wc 输出 1 1 6,你应该翻转它们.

If you want to show the wc output 1 1 6, you should flip them.

这篇关于子进程的行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆