1. 父子进程 pipe 通信
--
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
pid_t pid;
int pipe_fds[2];
char buffer[32];
int result;
memset(buffer, 0, 32);
result = pipe(pipe_fds);
if(result == -1) {
printf("pipe error!\n");
exit(1);
}
pid = fork();
if(pid < 0) {
printf("fork error!\n");
exit(0);
} else if(pid == 0) { // child
close(pipe_fds[1]);
sleep(3);
if(-1 != read(pipe_fds[0], buffer, 32))
printf("receive data from parent, %s!\n", buffer);
else
printf("read error!\n");
close(pipe_fds[0]);
} else if(pid > 0) { // parent
close(pipe_fds[0]);
sleep(1);
char *word = "hello";
if(-1 != write(pipe_fds[1], word, strlen(word)))
printf("send data to child, %s!\n", word);
else
printf("write error!\n");
close(pipe_fds[1]);
exit(0);
}
================================================================================
--
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
pid_t pid;
int pipe_fds[2];
char buffer[32];
int result;
memset(buffer, 0, 32);
result = pipe(pipe_fds);
if(result == -1) {
printf("pipe error!\n");
exit(1);
}
pid = fork();
if(pid < 0) {
printf("fork error!\n");
exit(0);
} else if(pid == 0) { // child
close(pipe_fds[1]);
sleep(3);
if(-1 != read(pipe_fds[0], buffer, 32))
printf("receive data from parent, %s!\n", buffer);
else
printf("read error!\n");
close(pipe_fds[0]);
} else if(pid > 0) { // parent
close(pipe_fds[0]);
sleep(1);
char *word = "hello";
if(-1 != write(pipe_fds[1], word, strlen(word)))
printf("send data to child, %s!\n", word);
else
printf("write error!\n");
close(pipe_fds[1]);
exit(0);
}
================================================================================
0 件のコメント:
コメントを投稿