簡體   English   中英

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 83436

光標停留在這里,直到按Enter鍵。

我試圖在沒有管道的情況下這樣做,只是編寫了一個簡單的程序:

#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#總計84

drwxr-xr-x 3根根4096 Mar 30 06:49。

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

-rwxr-xr-x 1根根16960 Mar 30 06:49點

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

問題是

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

使用WNOHANG您告訴waitpid輪詢狀態,然后立即返回實際退出等待狀態。

waitpid調用返回時,您退出父進程,而使兩個子進程變為孤立狀態。

當父進程退出時會發生什么,就是它的父進程(shell)接管並打印提示。 然后,您的子進程將輸出其輸出。 按下以“清除”輸出的Enter鍵只是外殼的空輸入。

您需要等待兩個子進程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM