进程间通信

来源:互联网 发布:知商金融活动 编辑:程序博客网 时间:2024/06/17 02:42

在进程间的通信手段大概分为以下几种:

1. 管道(Pipe)和有名管道(FIFO)

2. 信号(Signal)

3. 消息队列

4. 共享内存

5. 信号量

6. 套接字

今天我主要学习了管道,信号和共享内存三种方法,我主要复习管道的用法。

管道分为pipe 和 fifo 两种:

pipe 的创建:int pipe(int fd[2])。

管道两端分别用fd[0]和fd[1]描述,管道两端的任务固定,fd[0]只能用于读,称为管道读端;fd[1]只能用于写,称为管道写端。如果某进程要读取管道中的数据,那么该进程应当关闭fd[1],同时向管道写数据的进程应当关闭fd[0]。向管道中写数据类似。

例程:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>

int main()
{
int fd[2] = {0};
int ret = pipe(fd);

if (-1 == ret)
{
perror("pipe");
exit(1);
}

pid_t pid = fork();

if (-1 == pid)
{
perror("fork");
exit(2);
}

char buffer[32] = {0};

if (0 == pid)
{
while(1)
{
if (-1 == read(fd[0], buffer, 32))
{
perror("read");
exit(3);
}

printf("c recv: %s\n", buffer);
if (strcmp(buffer, "exit") == 0)
{
exit(0);
}
if (-1 == write(fd[1], buffer, 32))
{
perror("write");
exit(4);
}
sleep(1);
memset(buffer, 0, 32);
}
}
else
{
while(1)
{
printf("p scanf : ");
scanf("%s", buffer);
if (-1 == write(fd[1], buffer, 32))
{
perror("write");
exit(4);
}
if (strcmp(buffer, "exit") == 0)
{
exit(0);
}
sleep(1);
if (-1 == read(fd[0], buffer, 32))
{
perror("read");
exit(3);
}
printf("p recv : %s\n", buffer);

}
exit(0);
}
}

fifo 的创建: 

mkfifo("/root/Desktop/fifo/myfifo", S_IRWXU);(前面是标明创建的路径,后面是标明创建文件的权限)

完整创建fifo:
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>

int main()
{
int fd = mkfifo("/root/Desktop/fifo/myfifo", S_IRWXU);
if (-1 == fd)
{
perror("mkfifo");
exit(1);
}
}

fifo创建后,存在与硬盘上,必须先用open()将其打开。打开fifo的进程可能会被阻塞,如果同时以读写方式打开,则一定不会阻塞。如果以只读方式打开,则调用open的进程将会被阻塞直到有写方打开管道。

例程:

/*write*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
int fd = open("./myfifo", O_WRONLY);
if (-1 == fd)
{
perror("open");
exit(1);
}
char buf[32] = "hello";
if (-1 == write(fd, buf, 5))
{
perror("write");
exit(2);
}
close(fd);
return 0;
}

/*read*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
int fd = open("./myfifo", O_RDONLY);
if (-1 == fd)
{
perror("open");
exit(1);
}
char buf[32] = {0};
if (-1 == read(fd, buf, 5))
{
perror("read");
exit(2);
}
printf("%s\n", buf);

close(fd);

return 0;
}

原创粉丝点击