管道跳过睡觉。写多个字符串

时间:2015-04-28 16:48:01

标签: c pipe

我有这个代码,它应该将这三个语句写入管道,并且父代必须输出带有时间戳的管道中的任何内容。这些字符串必须按顺序排列。

int main(){
seedRandGen();
int k, pipes[2], pID, buflen;
char buff[BUFLEN + 1];
if(pipe(pipes) == 0){
    pID = fork();
    while(1){
        if(pID == 0){
            //CHILD
            //k = read(pipes[PIPEIN],buff,BUFLEN);
            const char *m1 = {"Breathing gas levels are adjusted."};
            const char *m2 = {"Light and Temperature levels are adjusted."};
            const char *m3 = {"Navigation adjustment made correctly."};
            sleep(getRandInt(3));
            k = write(pipes[PIPEOUT],m1,strlen(m1));
            sleep(getRandInt(6));
            k = write(pipes[PIPEOUT],m2,strlen(m2));
            sleep(getRandInt(3));
            k = write(pipes[PIPEOUT],m3,strlen(m3));
            //
            //  
        }
        else if(pID < 0){
            //FAILED TO FORK
            printf("Unable to open pipe. Everyone is dead. Good job.\n");
        }
        else{
            //PARENT
            if(!printed){
                printf("[%s]: %s\n", printTime(), "Spaceship Management System Start");
                printed = 1;
            }
            k = read(pipes[PIPEIN],buff,sizeof(buff));
            buff[k] = 0;
            printf("[%s]: %s\n",printTime(),buff);
        }
    }
}
close(pipes[PIPEIN]);
close(pipes[PIPEOUT]);
return 0;
}

seedRandGen()getRandInt()作为输出您期望的功能。管道应该一次只输出一个字符串,从m1到m3。但是,输出结果却说明了一个不同的故事:

[2015-04-28 11:43:12]: Breathing gas levels are adjusted.
[2015-04-28 11:43:16]: Light and Temperature levels are adjusted.Navigation adjustment made correctly.
[2015-04-28 11:43:17]: Breathing gas levels are adjusted.Light and Temperature levels are adjusted.Navigation adjustment made correctly.Breathing gas levels are adjusted.
[2015-04-28 11:43:21]: Light and Temperature levels are adjusted.Navigation adjustment made correctly.
[2015-04-28 11:43:22]: Breathing gas levels are adjusted.Light and Temperature levels are adjusted.Navigation adjustment made correctly.
[2015-04-28 11:43:24]: Breathing gas levels are adjusted.
[2015-04-28 11:43:25]: Light and Temperature levels are adjusted.
[2015-04-28 11:43:26]: Navigation adjustment made correctly.
[2015-04-28 11:43:28]: Breathing gas levels are adjusted.
[2015-04-28 11:43:31]: Light and Temperature levels are adjusted.Navigation adjustment made correctly.

在某些时候,管道中会写入多个字符串,就像孩子已经跳过睡眠一样。我不知道如何解决这个问题。我该怎么办?

0 个答案:

没有答案