【发布时间】:2010-02-28 23:12:43
【问题描述】:
我将命令行参数从父级传递到子级,并计算它们并打印。我的问题是我不确定我正在收割这个孩子吗?我不只需要一个出口 0 还是我需要再次调用 fork?
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int length = 0;
int i, n;
int fdest[2]; // for pipe
pid_t pid; //process IDs
char buffer[BUFSIZ];
if ((pid = fork()) < 0) /* attempt to create child / parent process */
{
printf("fork error");
}
if (pipe(fdest) < 0) /* attempt to create pipe */
printf("pipe error");
/* parent process */
else if (pid > 0) {
close(fdest[0]);
for(i = 1; i < argc; i++) /* write to pipe */
{
write(fdest[1], argv[i], strlen(argv[1]));
}
} else {
/* child Process */
close(fdest[1]);
for(i = 1; i < argc; i++)
{
length +=( strlen(argv[i])); /* get length of arguments */
}
n = read(fdest[0], buffer, length);
printf("\nchild: counted %d characters\n", n);
}
exit(0);
}
【问题讨论】:
-
僵尸可以在C中生孩子吗?我从不学习那种语言。
-
替换 printf("管道错误");带错误(“管道”);对于叉子也是如此。错误消息应该有用并写入标准错误。
标签: c