在Linux系统中,父子进程通讯(Inter-Process Communication, IPC)是指父进程与其子进程之间交换数据和信息的方式。这种通讯在多任务处理和程序设计中非常重要,可以实现数据共享、同步操作等功能。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main() {
int pipe_fd[2];
pid_t pid;
char buffer[256];
// 创建管道
if (pipe(pipe_fd) == -1) {
perror("pipe");
return 1;
}
pid = fork();
if (pid < 0) { // 错误处理
perror("fork");
return 1;
} else if (pid > 0) { // 父进程
close(pipe_fd[0]); // 关闭读端
const char *message = "Hello from parent!";
write(pipe_fd[1], message, strlen(message) + 1);
close(pipe_fd[1]); // 关闭写端
} else { // 子进程
close(pipe_fd[1]); // 关闭写端
read(pipe_fd[0], buffer, sizeof(buffer));
printf("Child received: %s
", buffer);
close(pipe_fd[0]); // 关闭读端
}
return 0;
}
通过理解这些基础概念和通讯方式,可以有效地解决父子进程间的通讯问题,并根据不同的应用场景选择合适的通讯机制。
领取专属 10元无门槛券
手把手带您无忧上云