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

 

#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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值