钟二网络头像

钟二网络

探索SQL查询技巧、Linux系统运维以及Web开发前沿技术,提供一站式的学习体验

  • 文章92531
  • 阅读1058762
首页 Linux 正文内容

linux实现进程通信

钟逸 Linux 2025-08-06 08:33:18 2

在Linux系统中,进程是独立运行的程序。为了实现进程之间的通信,有几种方式可用。本文将重点介绍管道、有名管道和消息队列这三种 。

管道

管道是一种单向的数据传输机制。它连接两个进程,一个进程作为写方,一个进程作为读方。写方进程将数据写入管道,而读方进程从管道中读取数据。管道是一种非持久性通信机制,也就是说,一旦管道被关闭,数据将丢失。

c

include

include

include

int main() {

int fd[2];

pipe(fd);

pid_t pid = fork();

if (pid == 0) {

// 子进程(写方)

close(fd[0]);

write(fd[1], "Hello from child\n", 16);

close(fd[1]);

} else {

// 父进程(读方)

close(fd[1]);

char buf[1024];

read(fd[0], buf, sizeof(buf));

close(fd[0]);

printf("Hello from parent: %s\n", buf);

}

return 0;

}

有名管道

有名管道与管道类似,但它是一个持久性通信机制。这意味着即使进程关闭,数据也不会丢失。有名管道可以在不同的进程之间共享。

c

include

include

include

include

int main() {

mkfifo("mypipe", 0666);

pid_t pid = fork();

if (pid == 0) {

// 子进程(写方)

int fd = open("mypipe", O_WRONLY);

write(fd, "Hello from child\n", 16);

close(fd);

} else {

// 父进程(读方)

int fd = open("mypipe", O_RDONLY);

char buf[1024];

read(fd, buf, sizeof(buf));

close(fd);

printf("Hello from parent: %s\n", buf);

}

return 0;

}

消息队列

消息队列是一种更高级的通信机制,允许进程交换消息而不直接连接。消息存储在内核中,进程可以将消息放入队列或从队列中获取消息。

c

include

include

include

include

int main() {

key_t key = ftok("myqueue", 1);

int msqid = msgget(key, IPC_CREAT | 0666);

pid_t pid = fork();

if (pid == 0) {

// 子进程(发送者)

struct msgbuf {

long mtype;

char mtext[1024];

};

struct msgbuf msg;

msg.mtype = 1;

strcpy(msg.mtext, "Hello from child");

msgsnd(msqid, &msg, sizeof(msg) - sizeof(long), 0);

} else {

// 父进程(接收者)

struct msgbuf msg;

msgrcv(msqid, &msg, sizeof(msg) - sizeof(long), 1, 0);

printf("Hello from parent: %s\n", msg.mtext);

}

return 0;

}

管道、有名管道和消息队列是在Linux系统中实现进程通信的常用 。管道适合简单的单向数据传输,有名管道适合持久性通信,而消息队列适合更高级的通信。选择哪种 取决于特定应用的需要。

文章目录
    搜索