国庆假期day4

作业: 完成父子进程的通信, 父进程发送一句话后,子进程接收打印 然后子进程发送一句话,父进程接收后打印

#include 
#include 
#include 
#include 
#include 
#include 

#define BUFFER_SIZE 100

typedef struct {
    int pipefd[2];
    char buffer[BUFFER_SIZE];
    int turn;
    pthread_cond_t cond;
    pthread_mutex_t mutex;
} SharedData;

void* childProcess(void* arg) {
    SharedData* sharedData = (SharedData*)arg;
    close(sharedData->pipefd[1]);  // 关闭写入端

    while (1) {
        pthread_mutex_lock(&sharedData->mutex);

        if (sharedData->turn == 0) {
            // 从父进程读取数据
            read(sharedData->pipefd[0], sharedData->buffer, BUFFER_SIZE);
            printf("子进程接收到的消息:%s\n", sharedData->buffer);

            sharedData->turn = 1;

            // 向父进程发送数据
            printf("请输入子进程发送的消息:");
            fgets(sharedData->buffer, BUFFER_SIZE, stdin);
            sharedData->buffer[strlen(sharedData->buffer) - 1] = '\0';  // 去除末尾的换行符

            write(sharedData->pipefd[1], sharedData->buffer, strlen(sharedData->buffer) + 1);

            pthread_cond_signal(&sharedData->cond);
        }

        pthread_mutex_unlock(&sharedData->mutex);
    }

    close(sharedData->pipefd[0]);  // 关闭读取端
    return NULL;
}

int main() {
    SharedData sharedData;
    pid_t pid;
    pthread_t tid;

    // 创建管道
    if (pipe(sharedData.pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    // 初始化共享数据
    sharedData.turn = 0;
    pthread_cond_init(&sharedData.cond, NULL);
    pthread_mutex_init(&sharedData.mutex, NULL);

    // 创建子进程和线程
    pid = fork();

    if (pid == -1) {  // 错误处理
        perror("fork");
        exit(EXIT_FAILURE);
    } 
    else if (pid == 0) {  // 子进程
        childProcess(&sharedData);
        exit(EXIT_SUCCESS);
    } 
    else {  // 父进程
        close(sharedData.pipefd[0]);  // 关闭读取端

        while (1) {
            pthread_mutex_lock(&sharedData.mutex);

            if (sharedData.turn == 1) {
                // 从终端输入数据,并向子进程发送
                printf("请输入父进程发送的消息:");
                fgets(sharedData.buffer, BUFFER_SIZE, stdin);
                sharedData.buffer[strlen(sharedData.buffer) - 1] = '\0';  // 去除末尾的换行符

                write(sharedData.pipefd[1], sharedData.buffer, strlen(sharedData.buffer) + 1);

                // 从子进程读取数据
                pthread_cond_wait(&sharedData.cond, &sharedData.mutex);

                read(sharedData.pipefd[0], sharedData.buffer, BUFFER_SIZE);
                printf("父进程接收到的消息:%s\n", sharedData.buffer);

                sharedData.turn = 0;
            }

            pthread_mutex_unlock(&sharedData.mutex);
        }

        close(sharedData.pipefd[1]);  // 关闭写入端
        wait(NULL);
        exit(EXIT_SUCCESS);
    }

    return 0;
}

你可能感兴趣的:(c#)