[parent.c]
#include <stdio.h>
#include <stdlib.h>
#include <="" span="">types.h>
#include <="" span="">wait.h>
#include <unistd.h>
char line[32];
char read_fd[3], write_fd[3];
int number, result;
int fd[2];
int st;
if (pipe(fd) <0){
perror("pipe");
exit (EXIT_FAILURE);
}
snprintf (read_fd, sizeof (read_fd),"%d", fd[0]);
snprintf (write_fd, sizeof (write_fd),"%d", fd[1]);
fgets (line, sizeof (line), stdin);
if (sscanf (line,"%d", &number) >0){
if (fork () == 0){
if (execl ("child", "child", read_fd, write_fd, NULL) <0){
exit (EXIT_FAILURE);
}
}
write (fd[1], &number, sizeof (number));
wait (&st);
read (fd[0], &result, sizeof (result));
printf ("%d x %d = %d\n", number, number, result);
close (fd[0]);
close (fd[1]);
}
return EXIT_SUCCESS;
}
[child.c]
#include <unistd.h>
int main (int argc, char *argv[]){
int number, result;
int read_fd, write_fd;
// 引数の文字列を整数に変換
read_fd = atoi (argv[1]);
write_fd = atoi (argv[2]);
// パイプラインからデータを読み込む
read (read_fd, &number, sizeof (number));
result = number*number;
// パイプラインにデータを書き込む
write (write_fd, &result, sizeof (result));
close (read_fd);
close (write_fd);
return EXIT_SUCCESS;
}
atmark@atde3:~/Desktop/work$ ./parent
3
3 x 3 = 9\natmark@atde3:~/Desktop/work$
0 件のコメント:
コメントを投稿