2013-03-12 29 views
0

我的问题很简单直接。这里我试图发送一个数据在pipe的一端,并试图从另一端读取。我试图学习IPC机制,并且在执行这个简单的程序时卡住了。如果我使用打印()[1]在父进程然后,为什么在使用管道的情况下,输出使用write()而不使用print()打印两次?

o/p is 

In the child process 
IN the parent process and its sleeping 
SUBI IS IN LOVE WITH PUTHALATH 

但是,如果我使用写()[2在下面的程序评价]在父进程

o/p is 

In the child process 
IN the parent process and its sleeping 
SUBI IS IN LOVE WITH PUTHALATHIN the parent process and its sleeping 

为什么“在父进程及其睡眠中”一行打印了两次?

#include<stdio.h> 
#include<unistd.h> 
#include<fcntl.h> 

int main(){ 

    int fd[2]; 
    pipe(fd); 

    if(!fork()){ 
    printf("In the child process\n"); 
    close(1); 
    dup(fd[1]); 
    close(fd[0]); 
    write(1,"SUBI IS IN LOVE WITH PUTHALATH", 200); 

    } else { 
     sleep(1); 
     printf("IN the parent process and its sleeping \n"); 
     char* stream; 
     close(fd[1]); 
     read(fd[0],stream,200); 
     printf("%s",stream);------>(1) 
     // write(1,stream,200);---->(2) 
    } 
    return 0; 
    } 

任何帮助请因为我卡在这里。

+1

注意:你没有为'stream'分配内存。因此'read'是未定义的行为。 – 2013-03-12 19:06:32

+0

'流'的名字很混乱。把它叫做buf并声明它是char buf [256];' – 2013-03-12 19:35:10

回答

0

在孩子,你

write(1,"SUBI IS IN LOVE WITH PUTHALATH", 200); 

将200字节写入管道,从字符串文字开始的位置开始。

write(1,stream,200); 
在父

(具有分配的内存stream后),则写写入到由子管内的200个字节,而printf停止在0字节终止字符串文字"SUBI IS IN LOVE WITH PUTHALATH"

所以无论字节在内存中的字符串文字是否打印出来。字符串文字"IN the parent process and its sleeping \n"显然位于该内存部分。

+0

>谢谢您的解释。 – 2013-03-13 17:19:25

+0

有一件事,我不明白是在孩子我从字符串的开始写200个字节。但字符串的实际长度只有30bytes.so那剩下的字节写入pipe.will它写入null对于200-30 = 170字节的剩余部分? – 2013-03-13 17:29:21

+0

你告诉它写200个字节,并且你给它一个寻找字节的地址(记住,所有'write'看到的“SUBI ...”是第一个字节的地址;'write' doesn' t知道它是一个字符串,所以当它到达0结束符时没有任何理由停止;直到它写入指定的200字节为止,或者由于访问冲突而停止[如果你告诉它写入多于缓冲区的大小,它很高兴地超越])。在字符串文字的31个字节(包括0-终止符)之后,它继续写下它后面存储的任何内容。 – 2013-03-13 19:50:20

0

BUGS

It is not advisable to mix calls to output functions from the stdio library 
    with low-level calls to write(2) for the file descriptor associated with 
    the same output stream; the results will be undefined and very probably not 
    what you want. 

http://man7.org/linux/man-pages/man3/puts.3.html

正如有人指出,你没有自己的视频流分配内存..

+0

>感谢提示。 – 2013-03-13 17:20:37

0

当我试图编译此,GCC说:

22:12: warning: ‘stream’ may be used uninitialized in this function 
[-Wuninitialized] 

这是一个重大的指示!

更改char *streamchar stream[200];并且按预期工作。但是如果你在最后调用write,你会写出远远超出字符串的任何内容,而且它不会被初始化为0,它可能是随机垃圾。您可以矫正这个:

write(1, stream, strlen(stream)); //correct length, not all 200 bytes 

真的,不过,你不应该在父写200个字节,因为你从你还没有分配的内存写入。数字应该等于字符串的长度(加上一个用于\0)。

+0

谢谢.i明白了。 – 2013-03-13 17:18:07

相关问题