Ubuntu系统中的进程间通信(IPC)有多种方法,以下是一些常见的IPC机制:
fcntl系统调用或者lockf函数。#include <stdio.h>
#include <unistd.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[10];
if (pipe(pipefd) == -1) {
perror("pipe");
return 1;
}
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid > 0) { // Parent process
close(pipefd[0]); // Close unused read end
write(pipefd[1], "Hello from parent", 20);
close(pipefd[1]);
} else { // Child process
close(pipefd[1]); // Close unused write end
read(pipefd[0], buffer, 10);
printf("Child received: %s\n", buffer);
close(pipefd[0]);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
int main() {
key_t key = 1234;
int shmid;
char *str;
// Create the shared memory segment
shmid = shmget(key, 1024, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(1);
}
// Attach the shared memory segment to the address space of the calling process
str = (char *) shmat(shmid, NULL, 0);
if (str == (char *) -1) {
perror("shmat");
exit(1);
}
// Write to the shared memory
strcpy(str, "Hello from shared memory!");
// Detach the shared memory segment
shmdt(str);
// Remove the shared memory segment
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
选择合适的IPC机制取决于具体的应用场景和需求。例如,如果需要高速数据交换且进程间有亲缘关系,共享内存可能是最佳选择;而如果需要在不同主机上的进程间通信,套接字则更为合适。