代码比较简单
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
int main ()
{
int fd[2];
int r = socketpair( AF_UNIX, SOCK_STREAM, 0, fd );
if ( r < 0 ) {
perror( "socketpair()" );
exit( 1 );
}
if ( fork() ) {
/* Parent process: echo client */
int val = 0;
close( fd[1] );
while ( 1 ) {
sleep( 1 );
++val;
printf( "Sending data: %d\n", val );
write( fd[0], &val, sizeof(val) );
read( fd[0], &val, sizeof(val) );
printf( "Data received: %d\n", val );
}
}
else {
/* Child process: echo server */
int val;
close( fd[0] );
while ( 1 ) {
read( fd[1], &val, sizeof(val) );
++val;
write( fd[1], &val, sizeof(val) );
}
}
}
测试结果:
$ make test
cc test.c -o test
$ ./test
Sending data: 1
Data received: 2
Sending data: 3
Data received: 4
Sending data: 5
Data received: 6
Sending data: 7
Data received: 8
Sending data: 9
Data received: 10
Sending data: 11
Data received: 12
Sending data: 13
Data received: 14
本文通过一个简单的C语言程序示例介绍了如何使用socketpair进行进程间通信。父进程作为客户端发送数据,子进程作为服务器接收并处理数据,再回传给父进程。该示例展示了基本的socketpair用法及父子进程间的交互。
4816

被折叠的 条评论
为什么被折叠?



