我試圖模擬呼叫者和使用管道接收器之間的談話。我分叉進程並使父進程成爲接收者,而子進程調用者。IPC使用fork()和管()
下面是代碼:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#define BUF_LEN 25
#define READ_END 0
#define WRITE_END 1
int main()
{
int fd[2];
if (pipe(fd) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
}
// the parent process is the receiver
if (pid > 0) {
close(fd[WRITE_END]);
char buffer[BUF_LEN + 1] = "";
do {
read(fd[READ_END], buffer, sizeof buffer);
if (strcmp(buffer, "")) {
printf("Received %s\n", buffer);
}
strcpy(buffer, "");
} while (strcmp(buffer, "Bye!"));
close(fd[READ_END]);
} else {
close(fd[READ_END]);
// const char *msg = "Hello";
char buffer[BUF_LEN + 1] = "";
bool end_call = false;
do {
printf("Caller: ");
fgets(buffer, sizeof buffer, stdin);
if (strcmp(buffer, "Bye!")) {
end_call = true;
}
// printf("Sent %s\n", buffer);
write(fd[WRITE_END], buffer, strlen(buffer) + 1);
} while (!end_call);
close(fd[WRITE_END]);
}
return 0;
}
但是當我運行它,我得到這個意外的輸出:
Caller: Hi
Received Hi
HI
Hello
Bye!
^C
接收器停止工作,但沒有收到我給的輸入。另外還有額外的換行符出現在輸出中。爲什麼會發生這種情況?
編輯: 正如Dmitri指出的那樣,我改變了調用者的strcmp測試和接收者的printf語句。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#define BUF_LEN 25
#define READ_END 0
#define WRITE_END 1
int main()
{
int fd[2];
if (pipe(fd) == -1) {
fprintf(stderr, "Pipe failed"); return 1; }
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
}
// the parent process is the receiver
if (pid > 0) {
close(fd[WRITE_END]);
char buffer[BUF_LEN + 1] = "";
do {
read(fd[READ_END], buffer, sizeof buffer);
if (strcmp(buffer, "")) {
printf("Received %s", buffer);
}
strcpy(buffer, "");
} while (strcmp(buffer, "Bye!"));
close(fd[READ_END]);
} else {
close(fd[READ_END]);
// const char *msg = "Hello";
char buffer[BUF_LEN + 1] = "";
bool end_call = false;
do {
printf("Caller: ");
fgets(buffer, sizeof buffer, stdin);
if (!strcmp(buffer, "Bye!")) {
end_call = true;
}
// printf("Sent %s\n", buffer);
write(fd[WRITE_END], buffer, strlen(buffer) + 1);
} while (!end_call);
close(fd[WRITE_END]);
}
return 0;
}
但收到「再見!」後仍不退出。
Caller: hi
Received hi
Caller: Hello
Received Hello
Caller: Bye!
Received Bye!
Caller: Bye!
Received Bye!
Caller: ^C
如果緩衝區足夠大,'fgets()'包含行尾的換行符。 – Dmitri
另外,如果'buffer' *不包含''Bye!',那麼你將'end_call'設置爲'true''' – Dmitri
@Dmitri:ok,但是爲什麼它不是在第一條消息之後退出? – In78