linux C语言开发管道通信实例

发布于:2024-08-21 ⋅ 阅读:(116) ⋅ 点赞:(0)

 

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

int pipe_default[2];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *writer_thread(void *arg)
{
    char buffer[100];
    memset(buffer, 0, sizeof(buffer));
    struct timespec tv;
    static int count = 0;  
    while (1)
    {
        ++count;
        clock_gettime(CLOCK_REALTIME, &tv); // 获取当前时间
        pthread_mutex_lock(&mutex);
        //  printf("序号=[%d]  定时时间   Current time: 秒=[%ld],纳秒=[%ld]\n", count, tv.tv_sec, tv.tv_nsec); // 打印当前时间
        sprintf(buffer, "序号=[%d]  定时时间   Current time: 秒=[%ld],纳秒=[%ld]\n", count, tv.tv_sec, tv.tv_nsec);
        write(pipe_default[1], buffer, strlen(buffer));
        printf("Send data to client, ok!\n");
        pthread_mutex_unlock(&mutex);
        sleep(5);
    }
}

void *reader_thread(void *arg)
{
    char buffer[100];
    memset(buffer, 0, sizeof(buffer));
    while (1)
    {
        pthread_mutex_lock(&mutex);       
        if (read(pipe_default[0], buffer, sizeof(buffer)) > 0)
        {
            printf("Receive data from server, %s\n", buffer);
        }
        pthread_mutex_unlock(&mutex);
        sleep(5);
    }
}

int main()
{
    if (pipe(pipe_default) < 0)
    {
        perror("Failed to create pipe!");
        return 1;
    }

    pthread_t tid_writer, tid_reader;
    pthread_create(&tid_writer, NULL, writer_thread, NULL);
    pthread_create(&tid_reader, NULL, reader_thread, NULL);

    pthread_join(tid_writer, NULL);
    pthread_join(tid_reader, NULL);

    return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到