我在使用C语言处理管道时遇到了严重的问题。我的目标是从命令行获取参数(例如:./myprogram 123 45 67),将每个字符逐个读入缓冲区,将字符发送给子进程进行计数,然后将读取的字符总数返回给父进程。以下是我的代码(注意:注释是我应该完成的内容):
// Characters from command line arguments are sent to child process
// from parent process one at a time through pipe.
// Child process counts number of characters sent through pipe.
// Child process returns number of characters counted to parent process.
// Parent process prints number of characters counted by child process.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
static int toChild[2];
static int fromChild[2];
static char buffer;
int main(int argc, char **argv)
{
int status;
int nChars = 0;
pid_t pid;
pipe(toChild);
pipe(fromChild);
if ((pid = fork()) == -1) {
printf("fork error %d\n", pid);
return -1;
}
else if (pid == 0) {
close(toChild[1]);
close(fromChild[0]);
// Receive characters from parent process via pipe
// one at a time, and count them.
int count = 0;
printf("child about to read\n");
while(read(toChild[0], &buffer, 1)){
count++;
}
// Return number of characters counted to parent process.
write(fromChild[1], &count, sizeof(count));
close(toChild[0]);
close(fromChild[1]);
printf("child exits\n");
}
else {
close(toChild[0]);
close(fromChild[1]);
// -- running in parent process --
printf("CS201 - Assignment 3 - Chris Gavette\n");
write(toChild[1], &argv[1], 1);
// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.
read(fromChild[0], &nChars, 1);
// Wait for child process to return. Reap child process.
// Receive number of characters counted via the value
// returned when the child process is reaped.
close(toChild[1]);
close(fromChild[0]);
waitpid(pid, &status, 0);
printf("child counted %d chars\n", nChars);
printf("parent exits\n");
return 0;
}
}
即使我关闭了两个管道的两个端口,子进程似乎仍然挂起。
fork
调用。你知道吗?第二个盲目地覆盖了第一个返回的pid。把第一个去掉。然后考虑一下你正在执行的所有读写调用,并问问自己来回发送的东西有多大。例如:write(toChild[1], &count, 1)
。嗯,count
是int
类型;为什么你只发送一个字节而不是sizeof(count)
?而且你的子循环退出条件最好还是有点问题。最后,如果你没有意识到的话,你应该为此使用两个管道描述符对,而不是一个。 - WhozCraig