一、基础概念
二、相关优势
三、类型及应用场景
ls | grep "txt"
,ls
命令的输出通过管道传递给grep
命令进行处理。#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[256];
if (pipe(pipefd)== -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程,关闭读端,向写端写入数据
close(pipefd[0]);
const char *message = "Hello from child process";
write(pipefd[1], message, strlen(message)+1);
close(pipefd[1]);
exit(EXIT_SUCCESS);
} else {
// 父进程,关闭写端,从读端读取数据
close(pipefd[1]);
read(pipefd[0], buffer, sizeof(buffer));
printf("Parent received: %s
", buffer);
close(pipefd[0]);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {
long mtype;
char mtext[100];
};
int main() {
key_t key;
int msgid;
struct msgbuf sbuf, rbuf;
key = ftok(".", 'a');
msgid = msgget(key, 0666 | IPC_CREAT);
// 发送消息
sbuf.mtype = 1;
strcpy(sbuf.mtext, "Hello from sender");
msgsnd(msgid, &sbuf, sizeof(sbuf.mtext), 0);
// 接收消息
msgrcv(msgid, &rbuf, sizeof(rbuf.mtext), 1, 0);
printf("Received: %s
", rbuf.mtext);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
int main() {
key_t key;
int shmid;
char *str;
key = ftok(".", 'b');
shmid = shmget(key, 1024, 0666 | IPC_CREAT);
str = (char *) shmat(shmid, (void *)0, 0);
strcpy(str, "Hello from shared memory");
printf("Data written in memory: %s
", str);
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
};
int main() {
key_t key;
int semid;
union semun arg;
struct sembuf sb = {0, -1, SEM_UNDO};
key = ftok(".", 'c');
semid = semget(key, 1, 0666 | IPC_CREAT);
arg.val = 1;
semctl(semid, 0, SETVAL, arg);
// 模拟临界区访问
semop(semid, &sb, 1);
printf("Entering critical section
");
sleep(2);
printf("Exiting critical section
");
sb.sem_op = 1;
semop(semid, &sb, 1);
semctl(semid, 0, IPC_RMID, arg);
return 0;
}
四、常见问题及解决方法
领取专属 10元无门槛券
手把手带您无忧上云