#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
int main()
{
int sync_fds[2];
if(socketpair(AF_UNIX, SOCK_STREAM, 0, sync_fds)){
perror("socketpair failed...\n");
return 0;
}
int child_pid = fork();
if(child_pid == -1){
perror("fork failed ...\n");
close(sync_fds[0]);
close(sync_fds[1]);
return 0;
}
if(child_pid){
close(sync_fds[0]);
char buff;
while(1){
sleep(1);
send(sync_fds[1], "C", 1, MSG_NOSIGNAL);
printf("parent: send c ....\n");
read(sync_fds[1], &buff, 1);
printf("parent: read %s\n", &buff);
}
}else{
close(sync_fds[1]);
char buff;
while(1){
int read_ret = read(sync_fds[0], &buff, 1);
printf("child read %s\n", &buff);
send(sync_fds[0], "D", 1, MSG_NOSIGNAL);
printf("child send d ...\n");
}
}
return 0;
}
输出结果:
parent: send c ....
child read C
child send d ...
parent: read D
parent: send c ....
child read C
child send d ...
parent: read D
parent: send c ....
child read C
child send d ...
parent: read D

本文介绍了一个使用socketpair进行父子进程间通信的C语言程序实例。该程序通过创建一对已连接的流套接字来实现双向通信,展示了父进程与子进程如何发送字符并接收反馈。
4594

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



