gpt4 book ai didi

c - 在 C 代码中带有管道的 linux 终端命令

转载 作者:太空宇宙 更新时间:2023-11-04 10:25:06 25 4
gpt4 key购买 nike

我正在尝试使用 C 代码中的简单管道执行 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

然后,您的子进程没有完成,因为管道仍在某处打开:在父进程中。事实上,您应该首先关闭描述符,然后等待您的 child 的进程。我会写:

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

关于c - 在 C 代码中带有管道的 linux 终端命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com