进程间的通信系统代码实现
时间: 2023-08-31 22:06:00 浏览: 42
进程间通信(IPC)是指在不同进程之间传递数据或者信号的机制。以下是一些常见的进程间通信方式的代码实现:
1. 管道通信:
```C
int fd[2];
pid_t pid;
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
close(fd[0]); // 子进程关闭读端
write(fd[1], "Hello, parent!", 14);
exit(EXIT_SUCCESS);
} else {
// 父进程
close(fd[1]); // 父进程关闭写端
char buf[256];
read(fd[0], buf, 256);
printf("%s\n", buf);
exit(EXIT_SUCCESS);
}
```
2. 共享内存通信:
```C
int fd = shm_open("/myshm", O_CREAT | O_RDWR, 0666);
ftruncate(fd, sizeof(int));
int *mem = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
*mem = 123;
exit(EXIT_SUCCESS);
} else {
// 父进程
sleep(1); // 等待子进程修改共享内存
printf("%d\n", *mem);
exit(EXIT_SUCCESS);
}
```
3. 消息队列通信:
```C
int msgid = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
struct mymsgbuf buf;
buf.mtype = 1;
strcpy(buf.mtext, "Hello, parent!");
msgsnd(msgid, &buf, sizeof(buf.mtext), 0);
exit(EXIT_SUCCESS);
} else {
// 父进程
struct mymsgbuf buf;
msgrcv(msgid, &buf, sizeof(buf.mtext), 1, 0);
printf("%s\n", buf.mtext);
msgctl(msgid, IPC_RMID, NULL); // 删除消息队列
exit(EXIT_SUCCESS);
}
```
以上代码仅供参考,实际使用时还需要根据具体情况进行修改和完善。