如何使用兩條管道用管父母和孩子之間發送消息父/子之間發送消息
我不能在我的代碼
這裏找出錯誤是我的代碼:
/* Using a pipe to send data from a parent to a child process
*/
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <string.h>
using namespace std;
int main(int argc, char *argv[ ]) {
int f_des[2];
int f_des2[2];
static char message[5];
if (argc != 2) {
cerr << "Usage: " << *argv << " message\n";
return 1;
}
if (pipe(f_des) == -1 || pipe(f_des2) == -1) { // generate the pipe
perror("Pipe");
return 2;
}
switch (fork()) {
case -1:
perror("Fork");
return 3;
case 0: // In the child
close(f_des[1]);
if (read(f_des[0], message, BUFSIZ) != -1) {
cout << "Message received by child: [" << message
<< "]" << endl;
cout.flush();
} else {
perror("Read");
return 4;
}
close(f_des[0]);
close(f_des2[0]);
if (write(f_des[1], argv[2], strlen(argv[2])) != -1) {
cout << "Message sent by child : [" <<
argv[1] << "]" << endl;
cout.flush();
} else {
perror("Write");
return 5;
}
break;
default: // In the Parent
close(f_des[0]);
if (write(f_des[1], argv[1], strlen(argv[1])) != -1) {
cout << "Message sent by parent : [" <<
argv[1] << "]" << endl;
cout.flush();
} else {
perror("Write");
return 6;
}
close(f_des[0]);
close(f_des2[0]);
if (read(f_des[0], message, BUFSIZ) != -1) {
cout << "Message received by parent: [" << message
<< "]" << endl;
cout.flush();
} else {
perror("Read");
return 7;
}
}
return 0;
}
您的代碼存在一些有問題的格式錯誤,需要列出具體問題,代碼應如何正常運行以及可驗證的結果。 – Stephen
有關正確格式化發佈的代碼的說明,請參閱stackoverflow.com的幫助中心。 –