[英]Why is the output printed twice with write() and not with print() in IPC using pipe?
我的問題很簡單明了。在這里,我試圖在管道的一端發送數據並試圖從另一端讀取數據。我正在嘗試學習IPC機制,在做這個簡單的程序時卡住了。然后在父進程中使用print()[1],
o/p is
In the child process
IN the parent process and its sleeping
SUBI IS IN LOVE WITH PUTHALATH
但是,如果我在父進程中使用write()[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;
}
任何幫助,因為我被困在這里。
臭蟲
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
正如其他人指出的那樣,您沒有為流分配內存。
在孩子里,你
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"
顯然位於該內存部分中。
當我嘗試編譯它時,gcc說:
22:12: warning: ‘stream’ may be used uninitialized in this function
[-Wuninitialized]
這是一個主要跡象!
將char *stream
更改為char stream[200];
並且它按預期工作。 但是,如果您在結尾處調用該write
,則將在該字符串之后寫出任何內容,並且此后的任何內容都將存儲在內存中,並且由於未將其初始化為0,因此它可能是隨機垃圾。 您可以通過以下方式更正該錯誤:
write(1, stream, strlen(stream)); //correct length, not all 200 bytes
但是,實際上,您不應該在父對象中寫入200字節,因為您是從尚未分配的內存中寫入數據。 該數字應等於字符串的長度( \\0
加一)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.