繁体   English   中英

Linux终端命令与C代码中的管道

[英]linux terminal command with a pipe in c code

我正在尝试使用ac代码中的简单管道执行Linux命令“ ls -l | tail -n 2”。

我添加了您的提示,现在可以正常工作,但是输出并不完全正确。 它以单行而不是两行打印输出,并等待用户输入关闭。 这是新代码:

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

void main()
{
    char line[100];
    pid_t pid;
    int fd[2];
    int status;
    char* ls_arguments[] = {"ls", "-l", NULL};
    char* tail_arguments[] = {"tail", "-n", "2", NULL};
    pipe(fd);
    pid = fork();
    if(pid == 0)//ls client
    {
        close(1);
        dup(fd[1]);
        close(fd[0]);
        execvp("ls", ls_arguments);
    }
    pid = fork();
    if(pid == 0)//tail client
    {
        close(0);
    close(fd[1]);
        dup(fd[0]);
        execvp("tail", tail_arguments);
    }
    wait(pid, 0, WNOHANG);
    close(fd[0]);
    close(fd[1]);
}

这应该运行“ ls -l”命令并输出到管道,下一个“ tail”客户端将其作为输入并运行“ tail -n 2”命令并输出最终输出,但是终端什么也没打印。 有什么帮助吗?

首先,没有这样的wait功能,这是该man说的:

#include <sys/types.h>
#include <sys/wait.h>

pid_t wait(int *status);

pid_t waitpid(pid_t pid, int *status, int options);

我认为您打算使用waitpid

然后,您的子进程将无法完成,因为管道仍在某个位置打开:在父级中。 确实,您应该首先关闭描述符,然后等待您的子进程。 我会写:

  close(fd[0]);
  close(fd[1]);
  wait(NULL); // Wait for the first child to finish
  wait(NULL); // Wait fot the second one
  return 0;
}

代替:

  wait(pid, 0, WNOHANG);
  close(fd[0]);
  close(fd[1]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM