在 C 中使用管道,是的 | head 进入无限循环
Using Pipe in C, yes | head is going in an infinite loop
关注此 SO 问答
Connecting n commands with pipes in a shell?
我尝试执行 yes | head
但它在无限循环中运行或者它永远不会响应。什么问题。
我做了一些修改,这里是 运行 代码
#include <unistd.h>
struct command
{
const char **string;
};
辅助函数
pid_t start(command* command, pid_t pid, int* status, int in, int out) {
(void) pid;
pid_t cpid;
int childInt;
cpid = fork();
if (cpid == 0) {
if (in != 0)
{
dup2(in, 0);
close(in);
}
if (out != 1)
{
dup2(out, 1);
close(out);
}
execvp(c->string[0], c->string);
_exit(1);
}
waitpid(cpid, &childInt, 0);
}
*status = childInt;
return c->pid;
}
在我的主要功能中
for(int i = 0; i < n; i++)
//New command every loop
int p = pipe(fd);
if (p == 0)
{
start_command(c, 0, &status, in, fd[1]);
close(fd[1]);
in = fd[0];
}
continue;
}
dup2(in, 0);
如果要执行yes | head
,需要创建yes
和head
两个进程,并且需要用管道将它们连接起来。您没有执行此操作的代码,您只需执行 yes
并传递给它 | head
。这导致 yes
永远输出 "| head"
。
您不能只将 yes
和 | head
传递给 execvp
。您可以 execvp
一个 shell 并传递它 yes | head
因为 shell 有必要的代码来创建管道、产生多个进程并适当地连接它们。
关注此 SO 问答
Connecting n commands with pipes in a shell?
我尝试执行 yes | head
但它在无限循环中运行或者它永远不会响应。什么问题。
我做了一些修改,这里是 运行 代码
#include <unistd.h>
struct command
{
const char **string;
};
辅助函数
pid_t start(command* command, pid_t pid, int* status, int in, int out) {
(void) pid;
pid_t cpid;
int childInt;
cpid = fork();
if (cpid == 0) {
if (in != 0)
{
dup2(in, 0);
close(in);
}
if (out != 1)
{
dup2(out, 1);
close(out);
}
execvp(c->string[0], c->string);
_exit(1);
}
waitpid(cpid, &childInt, 0);
}
*status = childInt;
return c->pid;
}
在我的主要功能中
for(int i = 0; i < n; i++)
//New command every loop
int p = pipe(fd);
if (p == 0)
{
start_command(c, 0, &status, in, fd[1]);
close(fd[1]);
in = fd[0];
}
continue;
}
dup2(in, 0);
如果要执行yes | head
,需要创建yes
和head
两个进程,并且需要用管道将它们连接起来。您没有执行此操作的代码,您只需执行 yes
并传递给它 | head
。这导致 yes
永远输出 "| head"
。
您不能只将 yes
和 | head
传递给 execvp
。您可以 execvp
一个 shell 并传递它 yes | head
因为 shell 有必要的代码来创建管道、产生多个进程并适当地连接它们。