fork() child exec 命令奇怪地输出

fork() child exec command outputting weirdly

我正在尝试执行 ls -la |厕所

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
    
int main(int argc, char **argv)
{
    int pipes=3;
    char *ls[] = {"ls","-la",NULL};
    char *wc[] = {"wc",NULL};
    char *base64[] = {"base64","-w0",NULL};
    //char **commands[] = {ls,wc,base64};

    int fds[pipes][2];
    for(int i=0;i<pipes;i++)
    {
        int err = pipe(fds[i]);
        if(err == -1)
        {
            perror("Pipe failed.\n");
        }
    }
    int status;
    pid_t childPid;
    //Child 1.
    if((childPid = fork()) == 0)    
    {
        dup2(fds[0][1],1);
        for(int i=0;i<pipes;i++)
        {
            close(fds[i][0]); 
            close(fds[i][1]);
        }
        execvp(ls[0],ls);
        exit(0);
    }
    else if(childPid == -1)
    {
        perror("Child 1 failed.\n");
    }
    // Second child.
    if((childPid = fork()) == 0)
    {
        dup2(fds[0][0],0);
        for(int i=0;i<pipes;i++)
        {
            close(fds[i][0]); 
            close(fds[i][1]);
        }
        execvp(wc[0],wc);
    }
    else if(childPid == -1)
    {
        perror("Child 2 failed.\n");
    }

    for(int i=0;i<pipes;i++)
    {
        close(fds[i][0]);
        close(fds[i][1]);
    }
    waitpid(childPid,&status,WUNTRACED|WNOHANG);
    return 0;
}

出乎意料:

root@danial#gcc -o pip pip.c

root@danial#./pip

10      83     436

我得到的输出:

root@danial#./pip

root@danial# 10 83 436

cursor stays here until I press enter key.

我试过不用管道来做这个,只是写了一个简单的程序:

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

int main(int argc, char **argv)
{
    if(fork() == 0)
    {
        execlp("ls","ls","-la",NULL);
        exit(0);
    }
    return 0;
}

同样的事情发生了:

root@danial#./test

root@danial#total 84

drwxr-xr-x 3 root root 4096 Mar 30 06:49 .

drwxr-xr-x 9 root root 4096 Mar 29 09:33 ..

-rwxr-xr-x 1 root root 16960 Mar 30 06:49 pip

-rw-r--r-- 1 root root 1310 Mar 30 06:48 pip.c

问题是这样的

waitpid(childPid,&status,WUNTRACED|WNOHANG);

使用 WNOHANG 告诉 waitpid 轮询状态,然后 return 立即 没有实际等待。

waitpid 调用 return 时,您退出父进程,使您的 两个 子进程成为孤儿。

而当父进程退出时会发生什么是它的父进程(shell)接管并打印提示。 然后 您的子进程打印它们的输出。您按 Enter 键 "clear" 输出只是 shell.

的空输入

您需要等待 两个 您的子进程。