我有一段代碼,我正在使用管道進行父和子進程之間的雙向讀寫操作。管道上的read()沒有被阻塞
從我讀過的內容來看,如果我不使用O_NONBLOCK,讀取應該阻塞,直到數據從另一端寫入管道。
但是,我注意到在父側的讀取沒有阻塞。我知道,因爲我正在gdb中進行調試,所以我已經將睡眠作爲第一條語句放在孩子的內部。
爲什麼read()by parent不在這裏阻塞?另外,還有什麼我需要做的以在兩個進程之間同步下面的讀/寫?
typedef struct
{
int x;
int y;
}PayLoad;
PayLoad pl;
bool b = false;
int pipe_fds[2];
void p(int i, int j)
{
pl.x = i;
pl.y = j;
pipe(pipe_fds);
pid_t cpid = fork();
if (cpid == 0) // child process
{
std::this_thread::sleep_for(std::chrono::seconds(100)); // just for debugging
close(pipe_fds[1]);
read(pipe_fds[0], &pl, sizeof(Payload));
//... do some processing on read data
close(pipe_fds[0]);
write(pipe_fds[1], &b, sizeof(bool));
close(pipe_fds[1]);
}
else if (cpid > 0) // parent process
{
close(pipe_fds[0]);
write(pipe_fds[1], &pl, sizeof(Payload));
close(pipe_fds[1]);
read(pipe_fds[0], &b, sizeof(bool)); <------ did not block!
close(pipe_fds[0]);
}
}
它返回什麼?檢查返回值!並且不要標記c,當它真的是C++時。 –
謝謝。只需添加代碼來檢查目前的閱讀回報。 – user2930006
您在閱讀之前關閉描述符 - 實際上,體面的錯誤處理會爲您節省一些時間 - 並且將來也會如此。 –