使用fgets fprintf
替代read write
讀寫管道
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <signal.h>
#include <string.h>
int main() {
pid_t pid;
int pipefd[2];
char buff[1024] = {0};
pipe(pipefd);
if ((pid = fork()) < 0) {
perror("fork");
return 1;
}
FILE *fp1 = fdopen(pipefd[1], "w");
if (pid == 0) {
while (1) {
close(pipefd[0]);
scanf("%[^\n]s", buff);
getchar();
fprintf(fp1, "%s\n", buff);
fflush(fp1);
}
}
else {
while (1) {
close(pipefd[1]);
FILE *fp2 = fdopen(pipefd[0], "r");
fgets(buff, 1024, fp2);
printf("server:%s", buff);
}
}
return 0;
}