#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <sys/ipc.h>
// Function to perform P (wait) operation
void P(int semaphoreId) {
struct sembuf sops;
sops.sem_num = 0; // Specify semaphore index in the set (0 in this case)
sops.sem_op = -1; // Wait operation
sops.sem_flg = 0; // Flags (usually set to 0)
semop(semaphoreId, &sops, 1); // Perform the semaphore operation
}
// Function to perform V (signal) operation
void V(int semaphoreId) {
struct sembuf sops;
sops.sem_num = 0; // Specify semaphore index in the set (0 in this case)
sops.sem_op = 1; // Signal operation
sops.sem_flg = 0; // Flags (usually set to 0)
semop(semaphoreId, &sops, 1); // Perform the semaphore operation
}
int main() {
int semaphoreId;
// Generate a unique key for the semaphore set
key_t key = ftok(".", 'S');
// Create or get the identifier of the semaphore set
semaphoreId = semget(key, 1, IPC_CREAT | 0666);
if (semaphoreId == -1) {
perror("semget");
exit(1);
}
// Initialize the semaphore to a value of 0
semctl(semaphoreId, 0, SETVAL, 0);
// 0 is write and 1 is read
int fd[2];
pid_t pid;
char buffer[20];
// Create a one-way communication channel (pipe)
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid > 0) { // Parent process
printf("Parent: Writing message to child\n");
char* msg = "Hello from parent";
// Write message to child
write(fd[1], msg, strlen(msg));
close(fd[1]); // Close the write end of the pipe
P(semaphoreId);
printf("**\n");
printf("Parent: waiting...\n");
// Read message from child
read(fd[0], buffer, sizeof(buffer));
sleep(1);
printf("Parent: Received: %s, from child!\n", buffer);
close(fd[0]);
} else { // Child process
close(fd[1]); // Close the write end of the pipe
// Read message from parent
read(fd[0], buffer, sizeof(buffer));
printf("Child: Received message: %s\n", buffer);
while (read(fd[0], buffer, sizeof(buffer)) > 0) {
// 读取并丢弃管道中的数据
}
printf("Child: Received message from parent!\n");
char* msg = "Hello from child";
write(fd[1], msg, strlen(msg));
close(fd[0]);
close(fd[1]);
printf("*\n");
V(semaphoreId);
}
return 0;
}
我添加了semaphore的代码如下: