这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <readline/readline.h>
#define NUMPIPES 2
int main(int argc, char *argv[]) {
char *bBuffer, *sPtr, *aPtr = NULL, *pipeComms[NUMPIPES], *cmdArgs[10];
int fdPipe[2], pCount, aCount, i, status, lPids[NUMPIPES];
pid_t pid;
pipe(fdPipe);
while(1) {
bBuffer = readline("Shell> ");
if(!strcasecmp(bBuffer, "exit")) {
return 0;
}
sPtr = bBuffer;
pCount = -1;
do {
aPtr = strsep(&sPtr, "|");
pipeComms[++pCount] = aPtr;
} while(aPtr);
for(i = 0; i < pCount; i++) {
aCount = -1;
do { …Run Code Online (Sandbox Code Playgroud) 我正在尝试在C中为我的shell实现多个管道.
我只有一个管道功能管道| b但不是| b | C.
int c[2];
int returnv;
pid_t id;
pipe(c);
pid = fork()) == 0
if (pid)
{
dup2(c[1], 0);
close(p[1]);
close(p[1]);
execvp(array(0), array);
}
if ((pid = fork()) == 0)
{
dup2(p[0], 1);
close(p(0));
close(p[0]);
returnv = execvp(array[0], array);
}
close(p[1]);
wait(NULL);
wait(NULL);
wait(NULL);
return returnv;
Run Code Online (Sandbox Code Playgroud)
这是第二个版本:
int i = 0;
while (i < x)
{
pipe(c);
if ((pid = fork()) == 0)
{
dup2(t[i], 1);
if (i < 2)
dup2(p[0], 1);
close(p[1]);
r= execvp(cmd[i][0], cmd[i]); …Run Code Online (Sandbox Code Playgroud) 这是代码:
int main() {
int fd[2];
pipe(fd);
int r = fork();
if (r > 0) { //parent
close(fd[0]);
// do a bunch of things
} else { //child
close(fd[1]);
// do a bunch of things
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是一段代码,其中父级写入管道,子级从管道读取。我的问题是:对于这两个 close 语句,它们到底关闭了什么?父母和孩子应该共享同一个文件,即 fd[0] 和 fd[1]。如果 fd[0] 在父级中关闭,它不应该在子级中也关闭吗?