Linux 下进程通信 IPC (Inter-Process Communication) 的常见方式有以下几种:
1. 管道(Pipe)和命名管道(FIFO):
- 管道是基于文件的 IPC 方式,用于在父子进程之间传递数据。
- 命名管道可用于任意进程之间的通信。
- 代码示例:
```c
#include
#include
#include
#include
int main() {
int fd[2];
pipe(fd);
pid_t pid = fork();
if (pid == 0) {
// 子进程
close(fd[1]); // 关闭写端
char buf[1024];
read(fd[0], buf, sizeof(buf));
printf("Child process received: %s\n", buf);
close(fd[0]); // 关闭读端
} else {
// 父进程
close(fd[0]); // 关闭读端
write(fd[1], "Hello from parent", 17);
close(fd[1]); // 关闭写端
waitpid(pid, NULL, 0);
}
return 0;
}
```
2. 消息队列(Message Queue):
- 消息队列是基于内核的 IPC 机制,允许进程间异步通信。
- 代码示例:
```c
#include
#include
#include
#include
struct message {
long mtype;
char mtext[200];
};
int main() {
key_t key = ftok(".", 'a');
int msgid = msgget(key, IPC_CREAT | 0666);
struct message msg;
msg.mtype = 1;
strcpy(msg.mtext, "Hello from sender");
msgsnd(msgid, &msg, sizeof(msg.mtext), 0);
msgrcv(msgid, &msg, sizeof(msg.mtext), 1, 0);
printf("Received message: %s\n", msg.mtext);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
```
3. 共享内存(Shared Memory):
- 共享内存是最高效的 IPC 机制,多个进程可以读写同一块内存区域。
- 代码示例:
```c
#include
#include
#include
#include
int main() {
key_t key = ftok(".", 'a');
int shmid = shmget(key, 1024, IPC_CREAT | 0666);
char *addr = (char *)shmat(shmid, NULL, 0);
strcpy(addr, "Hello from writer");
printf("Writer wrote: %s\n", addr);
shmdt(addr);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
```
4. 套接字(Socket):
- 套接字是基于网络的 IPC 机制,可用于本地或远程进程通信。
- 代码示例:
```c
#include
#include
#include
#include
#include
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
listen(sockfd, 5);
int connfd = accept(sockfd, NULL, NULL);
char buf[1024];
recv(connfd, buf, sizeof(buf), 0);
printf("Received: %s\n", buf);
close(connfd);
close(sockfd);
return 0;
}
```
这些只是 Linux 下 IPC 的几种常见方式,还有信号量、信号等其他机制。选择合适的 IPC 方式需要根据具体的应用场景和需求来决定。