您的位置:首页 > 大数据 > 人工智能

使用socketpair进行父子进程通信

2016-11-03 14:19 405 查看
代码比较简单
#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

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  进程通信