练习
设计两个没有血缘关系的进程,使用有名管道一个进程获取当前系统时间给另外一个进程
设计两个没有血缘关系的进程,使用有名管道一个进程获取当前系统时间给另外一个进程
登录后即可发布作业,立即登录
我的作业
全部作业 97
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;
}
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(¤tTime);
strcpy(buffer, asctime(tm_info));
int wbytes = 0;
wbytes = write(fd, buffer, strlen(buffer) + 1);
close(fd);
return 0;
}
执行结果:
linux@linux:~/learn/chapter12/new/job4-2$ ./read
获取到26字节的数据:Mon Apr 28 11:05:36 2025