#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
int pfd[2] = {0};
int pfd1[2] = {0};
if (pipe(pfd) < 0)
{
perror("pipe pfd");
return -1;
}
if (pipe(pfd1) < 0)
{
perror("pipe pfd1");
return -1;
}
pid_t pid = fork();
if (pid > 0)
{
// pfd父进程写,pfd1父进程读。
char buf[128] = "";
char buf1[128] = "";
while (1)
{
close(pfd[0]);
close(pfd1[1]);
bzero(buf, sizeof(buf));
printf("父发给子:");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
if (write(pfd[1], buf, sizeof(buf)) < 0)
{
perror("write");
return -1;
}
if(strcmp(buf,"quit")==0)
{
break;
}
bzero(buf1, sizeof(buf1));
if (read(pfd1[0], buf1, sizeof(buf1)) < 0)
{
perror("read");
return -1;
}
if(strcmp(buf1,"quit")==0)
{
break;
}
printf("父接收到子:%s\n", buf1);
}
close(pfd1[0]);
close(pfd[1]);
wait(NULL);
printf("父进程退出\n");
}
else if (0 == pid)
{
// pfd子进程写,pfd1子进程读。
close(pfd[1]);
close(pfd1[0]);
char buf[128] = "";
char buf1[128] = "";
while (1)
{
bzero(buf, sizeof(buf));
if (read(pfd[0], buf, sizeof(buf)) < 0)
{
perror("read");
return -1;
}
if(strcmp(buf,"quit")==0)
{
break;
}
printf("子接收到父:%s\n", buf);
bzero(buf1, sizeof(buf1));
printf("子发给父:");
fgets(buf1, sizeof(buf1), stdin);
buf1[strlen(buf1) - 1] = '\0';
if (write(pfd1[1], buf1, sizeof(buf1)) < 0)
{
perror("write");
return -1;
}
if(strcmp(buf1,"quit")==0)
{
break;
}
}
close(pfd1[1]);
close(pfd[0]);
printf("子进程退出\n");
}
else
{
perror("fork");
return -1;
}
return 0;
}
创建父子进程,实现父子进程的通话。
于 2022-11-15 21:51:06 首次发布