37 lines
763 B
C
37 lines
763 B
C
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <stdio.h>
|
|
|
|
#define MAX_BUFF 1024
|
|
|
|
int main(int argc, char **argv) {
|
|
/* fd[0] read, fd[1] write */
|
|
int fd[2];
|
|
pid_t pid;
|
|
char buff[MAX_BUFF];
|
|
|
|
if (pipe(fd) < 0) {
|
|
printf("pipe fails\n");
|
|
return -1;
|
|
}
|
|
|
|
if ((pid = fork()) < 0) {
|
|
printf("fork fails\n");
|
|
return -1;
|
|
} else if (pid > 0) {
|
|
char *msg = "Msg from parent process";
|
|
// parent process
|
|
// 关闭读端,写消息
|
|
close(fd[0]);
|
|
write(fd[1], msg, strlen(msg));
|
|
} else {
|
|
// child process
|
|
// 关闭写端,读消息
|
|
close(fd[1]);
|
|
read(fd[0], buff, MAX_BUFF);
|
|
printf("Read msg: %s\n", buff);
|
|
}
|
|
|
|
return 0;
|
|
}
|