简体   繁体   English

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

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

I'm trying to execute the Linux command "ls -l | tail -n 2" with a simple pipe in ac code. 我正在尝试使用ac代码中的简单管道执行Linux命令“ ls -l | tail -n 2”。

I added your tips and now this works but the output isn't exactly as it should be. 我添加了您的提示,现在可以正常工作,但是输出并不完全正确。 It prints the output in a single line instead of two and waits for a user input to close. 它以单行而不是两行打印输出,并等待用户输入关闭。 here is the new code: 这是新代码:

#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]);
}

this should run the "ls -l" command and output to the pipe and the next "tail" client would get it as input and run the "tail -n 2" command and print out the final output but the terminal prints nothing. 这应该运行“ ls -l”命令并输出到管道,下一个“ tail”客户端将其作为输入并运行“ tail -n 2”命令并输出最终输出,但是终端什么也没打印。 Any help? 有什么帮助吗?

First of all, there is not such wait function, here is what the man says: 首先,没有这样的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);

I think you meant to use waitpid . 我认为您打算使用waitpid

Then, you child process doesn't finish because the pipe is still opened somewhere: in the parent. 然后,您的子进程将无法完成,因为管道仍在某个位置打开:在父级中。 Indeed you should first close the descriptors and then wait for your childs process. 确实,您应该首先关闭描述符,然后等待您的子进程。 I would write: 我会写:

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

Instead of: 代替:

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

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

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