因此,内存中该字符串文字后面的任何字节也会被打印出来.字符串文字"IN the parent process and its sleeping \n"显然位于该内存部分中.My question is simple and straight forward.Here i am trying to send a data at the one end of pipe and trying to read from the other end.I am trying to learn IPC mechanism and i got stuck while doing this simple program.if i am using print()[1] in the Parent process then ,o/p isIn the child processIN the parent process and its sleepingSUBI IS IN LOVE WITH PUTHALATHBut if i am using write()[2 commented in the below program] in the parent process 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 sleepingWhy is the line "IN the parent process and its sleeping" got printed twice?#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; }Any help pls because i am stuck here. 解决方案 In the child, youwrite(1,"SUBI IS IN LOVE WITH PUTHALATH", 200);write 200 bytes to the pipe, starting from where the string literal begins.When youwrite(1,stream,200);in the parent (after having allocated memory to stream), you write the 200 bytes written to the pipe by the child, while the printf stops at the 0 byte terminating the string literal "SUBI IS IN LOVE WITH PUTHALATH".So whatever bytes follow that string literal in memory get printed out too. The string literal "IN the parent process and its sleeping \n" is apparently located within that memory section. 这篇关于为什么在IPC中使用管道使用write()而不使用print()将输出打印两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-21 00:54