プロセス間通信----双方向(fork,pipe)(list_73-1.c)
#include <stdio.h>
#define totalN 45
void do_child(int pfd1[2],int pfd2[2])
{
int ci;
char *p,nbuf;
char N[10] = "0123456789";
close(pfd1[1]);
close(pfd2[0]);
ci = nbuf = 0;
while(nbuf < totalN){
read(pfd1[0],&nbuf,1);
write(1,N+ci++,1);
if(ci >= 10) ci = 0;
nbuf++;
write(pfd2[1],&nbuf,1);
}
}
void do_parent(int pfd1[2],int pfd2[2])
{
int pi,status;
char *p,nbuf,count;
char A[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
close(pfd1[0]);
close(pfd2[1]);
pi = nbuf = 0;
while(nbuf < totalN){
write(1,A+(pi++),1);
if(pi >= 26) pi = 0;
nbuf++;
write(pfd1[1],&nbuf,1);
read(pfd2[0],&nbuf,1);
}
if(wait(&status) < 0) {
perror("wait");
exit(1);
}
putchar('\n');
}
int main()
{
int child,errno;
int pfd1[2],pfd2[2];
if(pipe(pfd1) < 0) {
perror("pipe1"); exit(1);
}
if(pipe(pfd2) < 0) {
perror("pipe2"); exit(1);
}
if((child=fork()) < 0) {
perror("fork");
exit(1);
}
if(child) do_parent(pfd1,pfd2);
else do_child(pfd1,pfd2);
return 0;
}
|
実行結果
A0B1C2D3E4F5G6H7I8J9K0L1M2N3O4P5Q6R7S8T9U0V1W2
|
|
プロセス間通信--双方向(fork,socketpair)(list_73-2.c)
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#define totalN 45
void do_child(int pfd)
{
int ci;
char *p,nbuf;
char N[10] = "0123456789";
ci = nbuf = 0;
while(nbuf < totalN){
read(pfd,&nbuf,1);
write(1,N+ci++,1);
if(ci >= 10) ci = 0;
nbuf++;
write(pfd,&nbuf,1);
}
}
void do_parent(int pfd)
{
int pi,status;
char *p,nbuf,count;
char A[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pi = nbuf = 0;
while(nbuf < totalN){
write(1,A+(pi++),1);
if(pi >= 26) pi = 0;
nbuf++;
write(pfd,&nbuf,1);
read(pfd,&nbuf,1);
}
if(wait(&status) < 0) {
perror("wait");
exit(1);
}
putchar('\n');
}
int main()
{
int child,errno;
int pipe_fd[2];
if(socketpair(AF_UNIX,SOCK_STREAM,0,pipe_fd) == -1) {
perror("socketpair");
exit(1);
}
if((child=fork()) < 0) {
perror("fork");
exit(1);
}
if(child) do_parent(pipe_fd[0]);
else do_child(pipe_fd[1]);
return 0;
}
|
実行結果
A0B1C2D3E4F5G6H7I8J9K0L1M2N3O4P5Q6R7S8T9U0V1W2
|
|