我正在尝试编写一个程序。父进程将获取main()函数的参数,并通过管道向子进程逐个发送其中的字符(每个字符调用一次write)。子进程将计算由父进程发送到它的字符数量,并打印出其接收自父进程的字符数。子进程不应以任何方式使用main()函数的参数。子进程应平稳返回而不是由父进程杀死。
我是否正确计算了参数?我是否逐个发送参数,我是否回收了子进程?
我是否正确计算了参数?我是否逐个发送参数,我是否回收了子进程?
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define size = 100;
int main(int argc, char *argv[])
{
int i, count =0;
int c;
int fdest[2]; // for pipe
pid_t pid; //process IDs
char buffer[BUFSIZ];
if (pipe(fdest) < 0) /* attempt to create pipe */
perror( "pipe" );
if ((pid = fork()) < 0) /* attempt to create child / parent process */
{
perror( "fork" );
}
/* parent process */
else if (pid > 0) {
close(fdest[0]);
for (i=1; i < argc; ++i)
{
for (c=0; c < strlen(argv[i]); ++c) {
write(fdest[1], &argv[i][c], 1);
}
}
close(fdest[1]);
wait(NULL);
exit(0);
} else {
/* child Process */
close(fdest[1]);
while (read(fdest[0], &buffer, 1) > 0)
{
count++;
}
printf("\nchild: counted %d characters\n", count);
}
wait(NULL);
exit(0);
}