在这个例子中,你可以看到execlp()函数和fork()的函数:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
pid_t pid;
char *pathvar;
char newpath[1000];
pathvar = getenv("PATH");
strcpy(newpath, pathvar);
strcat(newpath, ":u/userid/bin");
setenv("PATH", newpath);
if ((pid = fork()) == -1)
perror("fork error");
else if (pid == 0) {
execlp("newShell", "newShell", NULL);
printf("Return not expected. Must be an execlp error.n");
}
}
在这里你可以看到如何使两种工艺之间的管道:
/*
“ls -R | grep <pat>” where <pat> is a pattern
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv [])
{
int pipe1[2];
int pid1;
int pid2;
char stringa[100];
pipe(pipe1); // creo la pipe
if((pid1=fork())==0)
{
close(pipe1[0]);
dup2(pipe1[1],1);
close(pipe1[1]);
execlp("ls","ls","-R",NULL);
}
if((pid2=fork())==0)
{
close(pipe1[1]);
dup2(pipe1[0],0);
close(pipe1[0]);
execlp("grep","grep",argv[1],NULL);
}
close(pipe1[0]);
close(pipe1[1]);
waitpid(pid1,NULL,0);
waitpid(pid2,NULL,0);
exit(0);
}
谢谢你的回答。第二个例子更接近我所需要的。这是我的问题。为什么在第二个过程中你不关闭fd的读取结束?为什么在父进程中关闭管道的读写? – zarzonis
匿名管道是一个通信通道,它将两个进程与一个共同的祖先进行连接。 每个管道都有进出。每个访问都有一个文件描述符。 当进程使用管道的一侧时,必须用close()关闭文件描述符。 – elviuz
我必须关闭我使用的管道或者我没有使用的那一侧? – zarzonis