Linux管道(pipe)是一种进程间通信(IPC)机制,它允许一个进程的输出直接作为另一个进程的输入。管道通常用于连接多个命令,形成一个命令链,以便将一个命令的输出传递给下一个命令作为输入。
管道文件属性:
pipe()
系统调用创建。mkfifo()
系统调用创建,并且可以通过文件系统访问。ls | grep "txt"
。问题:管道中的数据丢失或没有按预期传输。
原因:
解决方法:
匿名管道示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[256];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == 0) { // 子进程
close(pipefd[1]); // 关闭写端
read(pipefd[0], buffer, sizeof(buffer));
printf("子进程接收到的消息: %s\n", buffer);
close(pipefd[0]);
} else { // 父进程
close(pipefd[0]); // 关闭读端
write(pipefd[1], "Hello from parent!", 19);
close(pipefd[1]);
}
return 0;
}
命名管道示例:
// writer.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
int fd;
char *message = "Hello from writer!";
mkfifo("myfifo", 0666);
fd = open("myfifo", O_WRONLY);
write(fd, message, sizeof(message));
close(fd);
return 0;
}
// reader.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
int fd;
char buffer[256];
fd = open("myfifo", O_RDONLY);
read(fd, buffer, sizeof(buffer));
printf("Reader received: %s\n", buffer);
close(fd);
return 0;
}
在这个例子中,writer.c
创建了一个命名管道并向其中写入消息,而reader.c
打开同一个管道并读取消息。
请注意,为了运行这些示例,你需要分别编译writer.c
和reader.c
,然后先运行writer
程序,再运行reader
程序。
领取专属 10元无门槛券
手把手带您无忧上云