C管道通信写/读功能剪切文本

时间:2013-05-01 23:11:22

标签: c pipe communication

写入或读取功能总是剪切除第一个字母之外的所有内容。有谁知道为什么? 我有一个父亲和一个孩子与管道沟通。 在把它变成写入之前我检查了变量,它没有被剪切掉。

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

1 个答案:

答案 0 :(得分:1)

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

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

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

pid_t pid = fork();

if(pid == 0){

   ...

}else{

   ...

}