c - fork() 子执行命令输出奇怪

标签 c pipe fork exec

我正在尝试执行 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 轮询状态,然后立即返回,而无需实际等待。

waitpid调用返回时,您退出父进程,使您的两个子进程处于孤立状态。

当父进程退出时,其父进程(shell)接管并打印提示符。 然后你的子进程打印它们的输出。您按下“清除”输出的 Enter 键只是 shell 的空输入。

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

关于c - fork() 子执行命令输出奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55430745/

相关文章:

c - C 中的 Makefile - 没有创建目标的规则

c - 打印各种FILE信息

创建 n 个 child ,每个 child 都有自己的管道

c++ - 通过 fork 和 pipeline 调用 gnuplot 并更新绘图

c++ - 使用fork()和boost::asio的进程池

字符指针初始化

c - 字符数组的函数?

c - 执行 ps aux | 的程序grep 根 | wc -l 在 C 中使用管道

c - 将相同的信息发送到多个线程/套接字?

c++ - fork 进程有问题