c語言 使用fgets fprintf 替代read write 讀寫管道 進行進程通信

使用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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章