プロセス間通信--親から子へ(fork,pipe,dup)(list_73-1.c)
#include <stdio.h>
#include <time.h>
int pipe_fd[2];
void do_parent()
{
int status;
char stim[256],*p="Hello, my kid.";
time_t t = time(NULL);
struct tm* tm = localtime(&t);
strftime(stim,sizeof(stim),"%H:%M:%S",tm);
printf("this is child.\n");
close(pipe_fd[0]);
close(1);
dup(pipe_fd[1]);
close(pipe_fd[1]);
printf("%s -> %s\n",stim,p);
close(1);
if(wait(&status) < 0){
perror("wait");
exit(1);
}
}
void do_child()
{
int status;
char buf[256];
printf("this is parent.\n");
close(pipe_fd[1]);
close(0);
dup(pipe_fd[0]);
close(pipe_fd[0]);
while(gets(buf) > 0){
printf("%s\n",buf);
}
close(0);
}
int main()
{
int child;
if(pipe(pipe_fd) < 0){
perror("pipe");
exit(1);
}
if((child = fork()) < 0){
perror("fork");
exit(1);
}
if(child) do_parent();
else do_child();
return 0;
}
|
実行結果
Gami[102]% list_73-1.exe
this is child.
this is parent.
22:10:58 -> Hello, my kid.
Gami[103]%
|
|
プロセス間通信--子から親へ(fork,pipe,dup)(list_73-2.c)
#include <stdio.h>
#include <time.h>
int pipe_fd[2];
void do_parent()
{
int status;
char buf[256];
printf("this is parent.\n");
close(pipe_fd[1]);
close(0);
dup(pipe_fd[0]);
close(pipe_fd[0]);
while(gets(buf) > 0){
printf("%s\n",buf);
}
close(0);
if(wait(&status) < 0){
perror("wait");
exit(1);
}
}
void do_child()
{
char stim[256],*p="Hello, my parent.";
time_t t = time(NULL);
struct tm* tm = localtime(&t);
strftime(stim,sizeof(stim),"%H:%M:%S",tm);
printf("this is child.\n");
close(pipe_fd[0]);
close(1);
dup(pipe_fd[1]);
close(pipe_fd[1]);
printf("%s -> %s\n",stim,p);
close(1);
}
int main()
{
int child;
if(pipe(pipe_fd) < 0){
perror("pipe");
exit(1);
}
if((child = fork()) < 0){
perror("fork");
exit(1);
}
if(child) do_parent();
else do_child();
return 0;
}
|
実行結果
Gami[103]% list_73-2.exe
this is parent.
this is child.
22:11:38 -> Hello, my parent.
Gami[104]%
|
|