如何列印我卡住的 C 管道中的每個字串。
像這樣輸出
收到字串:spike
收到字串:spike
收到字串:spike
但我想要這樣
收到字串:spike
收到的字串:tom
接收字串:jerry
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[3][10] = {
"spike",
"tom",
"jerry"};
char readbuffer[80];
pipe(fd);
if ((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if (childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string) 1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
for (int i = 0; i < 3; i )
{
printf("Received string: %s \n", readbuffer);
}
}
return (0);
}
uj5u.com熱心網友回復:
你犯了幾個錯誤。
首先,孩子沒有將正確的東西寫入管道。然后你 read() 一個 80 位元組的緩沖區,它將包含所有 3 個字串(假設你已經修復了問題 1)。但是由于您寫入的位元組比字串的長度多一個位元組,因此您的讀取緩沖區中間將有一個零位元組。任何列印嘗試都將簡單地停止在該零位元組處。
添加錯誤處理很重要。您永遠不能假設讀取或寫入會成功。
我對您的代碼進行了一些修改,使其效果更好(但還不行):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
/* added newlines to separate the entries when printing */
char string[3][10] = {
"spike\n",
"tom\n",
"jerry\n"
};
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
/* Added a loop here, so all 3 entries are written */
for (int i = 0; i < 3; i) {
write(fd[1], string[i], (strlen(string[i])));
}
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
/* no loop needed here for now
But you'd need to read until you reach EOF.
I leave that as an exercise
*/
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
readbuffer[nbytes] = '\0';
printf("Received string: %s \n", readbuffer);
}
return(0);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/438998.html
