简体   繁体   English

如何使用时间函数并通过命名管道传递时间

[英]How to use time function and pass the time through named pipe

I am trying to create client server communication through named pipe.我正在尝试通过命名管道创建客户端服务器通信。 From my client I want to send current time.我想从我的客户那里发送当前时间。 I am trying to use time() function but the time won't appear on my server side terminal.我正在尝试使用time()函数,但时间不会出现在我的服务器端终端上。 I just see provided text.我只看到提供的文字。 What am I doing wrong?我究竟做错了什么?

server服务器

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

int main() {

    char *pathname = "/tmp/myfifo";
    int make_fifo = mkfifo(pathname, 0666);
    
    char str[80];
    for(;;){
        int opn = open(pathname, O_RDONLY);
        read(opn, str, sizeof(str));
        close(opn);

    }

    return 0;
}

client客户

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

int main() {

    char *pathname = "/tmp/myfifo";
    time_t current_time = time(0);
    char str[80];
    
    int fd = open(pathname, O_WRONLY);
    fgets(str, 80, stdin);  
    write(fd, str, sizeof(str));
    write(fd, (void*) current_time, sizeof(current_time));

    close(fd);
    return 0;
}

What am I doing wrong?我究竟做错了什么?

  1. client: Not passing the address of current_time .客户端:没有传递current_time的地址。 *1 *1

     // write(fd, (void*) current_time, sizeof(current_time)); write(fd, &current_time, sizeof(current_time)); // Add &
  2. server: not reading the time.服务器:不读时间。

  3. Ignoring return values of read()/write() .忽略read()/write()的返回值。


*1 Avoid casting like (void*) current_time . *1避免像(void*) current_time那样强制转换。 Casting tends to hide errors.铸造往往会隐藏错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM