通過在C 2管我試圖創建一個使用用C在Linux上2管父子進程之間的雙向通信。父母是我的程序,孩子只是一個隨機程序(說「貓」)。雙向親子溝通在Linux上
我嘗試在父母使用read()
閱讀孩子的輸出,但它給了我錯誤號9,這是錯誤的文件描述符。
下面是我的代碼
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define Read 0
#define Write 1
#define ParentRead read_pipe[1]
#define ParentWrite write_pipe[0]
#define ChildRead write_pipe[1]
#define ChildWrite read_pipe[0]
int main()
{
int data_processed;
/** Pipe for reading for subprocess */
int read_pipe[2];
/** Pipe for writing to subprocess */
int write_pipe[2];
char buffer[100];
memset(buffer, '\0', 100);
if (pipe(read_pipe) == 0 && pipe(write_pipe) == 0)
{
pid_t pid = fork();
if (pid == (pid_t)-1)
{
fprintf(stderr, "Fork failure");
exit(EXIT_FAILURE);
}
else if (pid == (pid_t)0) //Child process
{
close(Read);
close(Write);
close(ParentRead);
close(ParentWrite);
dup(ChildRead);
dup(ChildWrite);
execlp("cat", (char*)NULL);
exit(EXIT_FAILURE);
}
else { //Parent process
close(ChildRead);
close(ChildWrite);
write(ParentWrite, "abc", 3);
int r = read(ParentRead, buffer, 99);
printf("%d %d", r, errno);
puts(buffer);
}
}
exit(EXIT_SUCCESS);
}
open()在執行I/O之前的管道。 – 2012-02-16 20:13:09
不是(pipe(read_pipe)== 0 && pipe(write_pipe)== 0)與打開管道相同嗎? – Jeff 2012-02-16 20:48:14
是的,這是一樣的。 – mikithskegg 2012-02-16 20:54:19