Skip to content

Instantly share code, notes, and snippets.

@msymt
Last active April 18, 2022 07:09
Show Gist options
  • Save msymt/72a002919964b2cede5ca759e54692d8 to your computer and use it in GitHub Desktop.
Save msymt/72a002919964b2cede5ca759e54692d8 to your computer and use it in GitHub Desktop.
パイプによる親子プロセス間通信(parentが書き込み、childが読み込んで標準出力)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFSIZE 512
#define err(mess) { fprintf(stderr,"Error: %s.\n", mess); exit(1); }
int main(int argc, char *argv[]) {
int pfd[2]; // pipe file descriptors, pfd[0]: read, pdf[1]: write
char buf[BUFFSIZE];
ssize_t numRead;
if(argc != 2 || strcmp(argv[1], "--help") == 0) {
printf("Usage: %s <message>\n", argv[0]);
exit(1);
}
if(pipe(pfd) < 0) { // create the pipe
err("pipe");
}
switch(fork()) {
case -1:
err("fork");
case 0: // child - read from parent
if(close(pfd[1]) == -1) { // 書き込み口は不要
err("close");
}
for(;;) { // pipeを読み取り、stdoutへ出力
numRead = read(pfd[0], buf, BUFFSIZE);
if(numRead == -1) {
err("read");
}
if(numRead == 0) { // End-of-file
break;
}
if(write(STDOUT_FILENO, buf, numRead) != numRead) {
err("child - partial/failed write");
}
}
write(STDOUT_FILENO, "\n", 1);
if(close(pfd[0]) == -1) {
err("close");
}
_exit(EXIT_SUCCESS);
default: // parent - write to child
if(close(pfd[0]) == -1) { // 読み取り口は不要
err("close");
}
if(write(pfd[1], argv[1], strlen(argv[1])) != strlen(argv[1])) {
err("parent - partial/failed write");
}
if(close(pfd[1]) == -1) { // 子プロセスはEOFを読み取る
err("close");
}
wait(NULL); // Wait for child to finish
exit(EXIT_SUCCESS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment