【问题标题】:C Pipe communicating write/read function cuts of textC管道通信文本的写/读功能切割
【发布时间】:2013-05-01 23:11:21
【问题描述】:

write 或 read 函数总是删除除第一个字母之外的所有内容。有谁知道为什么? 我有一个用管道通信的父亲和一个孩子。 我在写入之前检查了这个变量,它没有被删除。

#include<dirent.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>

int main(int argc, char *argv[])
{
    time_t tm_now;
    struct tm *ptm_now;
    time(&tm_now);
    ptm_now = localtime(&tm_now);

    int chanal_father[2];
    int chanal_child[2];
    pipe(chanal_father);
    pipe(chanal_child);
    char message_child[50];
    char message_father[50];
    char message_return[50];


    if (fork()==0)
    {
        read(chanal_father[0], message_father, strlen(message_father)+1);
        if(strcmp(message_father, "day") == 0) {
            int day = ptm_now->tm_mday;
            int month = (ptm_now->tm_mon)+1;
            int year = (ptm_now->tm_year)-1900;         
            sprintf(message_return, "%2d.%2d.%2d", day, month, year);
        }
        else {
            sprintf(message_return, "unknown function!");
        }

        write(chanal_child[1],message_return, strlen(message_return)+1);
        exit(0);
    }

    write(chanal_father[1], argv[1], strlen(argv[1])+1);
    read(chanal_child[0], message_child, strlen(message_child)+1);
    printf("%s\n", message_child);
}

【问题讨论】:

  • strlen(message_father)+1 可能等于 1?字符串未初始化。你只读一个字节。管道不适用于可变长度消息。

标签: c pipe communication


【解决方案1】:

不要使用 strlen() 来获取数组的大小,使用 sizeof()。请记住 read() 将读取最多 'count' 个字节:

ssize_t read(int fd, void *buf, size_t count);

此外,为清楚起见,您可能希望按如下方式构建程序:

pid_t pid = fork();

if(pid == 0){

   ...

}else{

   ...

}

【讨论】:

  • 不同的是 strlen() 将确定字符串的长度。根据定义,C 中的字符串是一个以空值结尾的数组。由于您的数组未初始化,strlen() 将返回 0 作为长度。
  • 顺便说一句,else{} 块应该在您的代码中,否则该代码将由父子代码执行。
猜你喜欢
  • 2011-07-18
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多