进程间通讯-有名管道 学习任务
我要参与
进程间通讯-有名管道 学习任务
学习任务 2.1k
等97人参与
来源: 第12周 / 物联网/嵌入式工程师

练习

设计两个没有血缘关系的进程,使用有名管道一个进程获取当前系统时间给另外一个进程

去发布

登录后即可发布作业,立即

我的作业

全部作业 97

慕运维8597106

fifo_read.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define FIFO_NAME "./execise"

int main(int argc, char const *argv[])
{
    int ret;
    int fd;
    char buffer[64] = {0};
    ret = access(FIFO_NAME, F_OK);
    if (ret == -1)
    {
        mkfifo(FIFO_NAME, 0644);
    }
    fd = open(FIFO_NAME, O_RDWR);
    if (fd == -1)
    {
        perror("[ERROR] open():");
        exit(EXIT_FAILURE);
    }
    int rbytes = 0;
    rbytes = read(fd, buffer, sizeof(buffer));
    if (rbytes > 0)
    {
        printf("获取到%d字节的数据:%s", rbytes, buffer);
    }
    close(fd);
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
代码块
复制 预览
复制成功!

fifo_write.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>

#define FIFO_NAME "./execise"

int main(int argc, char const *argv[])
{
    int ret;
    int fd;
    char buffer[64] = {0};
    time_t currentTime;
    struct tm *tm_info;

    ret = access(FIFO_NAME, F_OK);
    if (ret == -1)
    {
        mkfifo(FIFO_NAME, 0644);
    }
    fd = open(FIFO_NAME, O_RDWR);
    if (fd == -1)
    {
        perror("[ERROR] open():");
        exit(EXIT_FAILURE);
    }

    currentTime = time(NULL);
    tm_info = localtime(&currentTime);
    strcpy(buffer, asctime(tm_info));
    int wbytes = 0;
    wbytes = write(fd, buffer, strlen(buffer) + 1);
    close(fd);
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
代码块
复制 预览
复制成功!

执行结果:

linux@linux:~/learn/chapter12/new/job4-2$ ./read
获取到26字节的数据:Mon Apr 28 11:05:36 2025
  • 1
  • 2
代码块
复制 预览
复制成功!
提交于  2025-04-28 11:04:22
评论 1
讲师点评
评分:100
无__名
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师