进程间通信之socketpair
socketpair是进程间通信的一种方式。
API:
int socketpair(int domain, int type, int protocol, int sv[2]);
DEMO:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#define MAXLINE 4096
int main(int argc, char **argv) {
int fd[2];
pid_t pid;
char line[MAXLINE];
int n;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
perror("socketpair error");
exit(1);
}
if ( (pid = fork()) < 0) {
perror("fork error");
exit(1);
} else if (pid > 0) {
close(fd[1]);
write(fd[0], "hello world\n", 12);
char tmp[MAXLINE];
read(fd[0], tmp, MAXLINE);
printf("echo is: %s\n", tmp);
} else {
close(fd[0]);
n = read(fd[1], line, MAXLINE);
write(STDOUT_FILENO, line, n);
char tmp[] = "world says hi";
write(fd[1], tmp, strlen(tmp));
}
exit(0);
}
和管道和命名管道相比,socketpair有以下特点:
全双工
可用于任意两个进程之间的通信
转载于//www.cnblogs.com/gattaca/p/6548098.html
还没有评论,来说两句吧...