在CentOS系统中,进程间通信(IPC)主要有以下几种方式:
fcntl系统调用来实现。#include <stdio.h>
#include <unistd.h>
int main() {
int pipefd[2];
char buffer[10];
if (pipe(pipefd) == -1) {
perror("pipe");
return 1;
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) { // 子进程
close(pipefd[1]); // 关闭写端
read(pipefd[0], buffer, sizeof(buffer));
printf("Child received: %s\n", buffer);
close(pipefd[0]);
} else { // 父进程
close(pipefd[0]); // 关闭读端
write(pipefd[1], "Hello from parent", 20);
close(pipefd[1]);
}
return 0;
}
# 创建命名管道
mkfifo myfifo
# 写入数据
echo "Hello" > myfifo &
# 读取数据
cat myfifo
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
key_t key = ftok("shmfile", 65);
int shmid = shmget(key, 1024, 0666|IPC_CREAT);
char *str = (char*) shmat(shmid, (void*)0, 0);
strcpy(str, "hello world");
printf("Shared memory segment: %s\n", str);
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
};
int main() {
key_t key = ftok("semfile", 65);
int semid = semget(key, 1, 0666|IPC_CREAT);
union semun arg;
arg.val = 1; // 初始化信号量为1
semctl(semid, 0, SETVAL, arg);
// P操作(等待信号量)
struct sembuf sb = {0, -1, SEM_UNDO};
semop(semid, &sb, 1);
printf("Semaphore value: %d\n", semctl(semid, 0, GETVAL, arg));
// V操作(释放信号量)
sb.sem_op = 1;
semop(semid, &sb, 1);
semctl(semid, 0, IPC_RMID, arg);
return 0;
}
这些示例展示了如何在CentOS系统中使用不同的IPC机制。根据具体需求选择合适的通信方式。