我试着在网上搜索,但几乎没有任何资源.一个小例子就足够了.
编辑我的意思是,两个不同的C程序相互通信.一个程序应发送"Hi",另一个程序应接收它.这样的事情.
我正在尝试编写一个程序,它将在它们之间产生任意数量的子进程和管道,类似于命令行管道.在我的情况下,我正在尝试"ls -l | more"并将其输出到stdout,然后让父级继续执行更多命令.
我将以下代码作为最小示例:
int main (int argc, const char * argv[]) {
int fd[2];
pipe(fd);
chdir("/directory/with/lots/of/files");
// Create one child process for more
int pid = fork();
if (pid == 0) {
close(fd[1]);
int ret = dup2(fd[0],0);
if (ret < 0) perror("dup2");
char *argv[10];
argv[0] = "more"; argv[1] = NULL;
execvp("more", argv);
}
// Create another child process for ls
int pid2 = fork();
if (pid2 == 0) {
int ret = dup2(fd[1],1);
if (ret < 0) perror("dup2"); …Run Code Online (Sandbox Code Playgroud)